|
| 1 | +import bindings from "bindings"; |
| 2 | +import fs from "node:fs" |
| 3 | + |
| 4 | +/** @type {ILibDectalk} */ |
| 5 | +const libdectalk = bindings("dectalk"); |
| 6 | + |
| 7 | +const toBytes = (number) => { |
| 8 | + return [0xff & number, |
| 9 | + 0xff & (number >> 8), |
| 10 | + 0xff & (number >> 16), |
| 11 | + 0xff & (number >> 24)] |
| 12 | +} |
| 13 | + |
| 14 | +/** @type {(text: string) => Promise<Buffer>} */ |
| 15 | +const say = (text) => { |
| 16 | + const format = 1; |
| 17 | + const audioBuffer = []; |
| 18 | + let dataLength = 0; |
| 19 | + |
| 20 | + /** @type {(chunkData: Buffer) => void} */ |
| 21 | + const callback = (chunkData) => { |
| 22 | + // copy the buffer immediately before its destroyed |
| 23 | + audioBuffer.push(Buffer.from(chunkData)); |
| 24 | + dataLength += chunkData.byteLength; |
| 25 | + } |
| 26 | + |
| 27 | + libdectalk.setCallback(callback) |
| 28 | + libdectalk.say(text, format); |
| 29 | + |
| 30 | + const sampleRate = format ? 11025 : 8000 |
| 31 | + const bufferLength = 44 + dataLength; |
| 32 | + |
| 33 | + // Generate a WAV header |
| 34 | + const header = Buffer.from([ |
| 35 | + 0x52, 0x49, 0x46, 0x46, // RIFF |
| 36 | + ...toBytes(bufferLength), // WAV size |
| 37 | + 0x57, 0x41, 0x56, 0x45, // WAVE |
| 38 | + 0x66, 0x6d, 0x74, 0x20, // fmt |
| 39 | + 0x10, 0x00, 0x00, 0x00, // fmt chunk size |
| 40 | + 0x01, 0x00, 0x01, 0x00, // Audio format 1=PCM & Number of channels 1=Mono |
| 41 | + ...toBytes(sampleRate), // Sampling Frequency in Hz |
| 42 | + ...toBytes(sampleRate * 2), // bytes per second |
| 43 | + 0x02, 0x00, 0x10, 0x00, // 2=16-bit mono & Number of bits per sample |
| 44 | + 0x64, 0x61, 0x74, 0x61, // data |
| 45 | + ...toBytes(dataLength) // data size |
| 46 | + ]) |
| 47 | + |
| 48 | + return Buffer.concat([header, ...audioBuffer]) |
| 49 | +} |
| 50 | + |
| 51 | +const buffer = say("This is a message from Node J S"); |
| 52 | +fs.writeFileSync("first.wav", buffer); |
| 53 | + |
| 54 | +const buffer2 = say("This is a second message from Node J S"); |
| 55 | +fs.writeFileSync("second.wav", buffer2); |
| 56 | +console.log("end of programme"); |
0 commit comments