|
| 1 | +const fs = require("fs"); |
1 | 2 | const { createClient, LiveTTSEvents } = require("../../dist/main/index"); |
2 | | -const fetch = require("cross-fetch"); |
3 | 3 |
|
4 | 4 | const live = async () => { |
5 | 5 | const text = "Hello, how can I help you today?"; |
6 | 6 |
|
7 | | - const deepgram = createClient(process.env.DEEPGRAM_API_KEY, { |
8 | | - global: { fetch: { options: { url: "https://api.beta.deepgram.com" } } }, |
9 | | - }); |
| 7 | + const deepgram = createClient(process.env.DEEPGRAM_API_KEY); |
| 8 | + |
| 9 | + const connection = deepgram.speak.live({ model: "aura-asteria-en" }); |
10 | 10 |
|
11 | | - const connection = deepgram.speak.live({ text }, { model: "aura-asteria-en" }); |
| 11 | + let audioBuffer = Buffer.alloc(0); |
12 | 12 |
|
13 | 13 | connection.on(LiveTTSEvents.Open, () => { |
| 14 | + console.log("Connection opened"); |
| 15 | + |
| 16 | + // Send text data for TTS synthesis |
| 17 | + connection.sendText(text); |
| 18 | + |
| 19 | + // Send Flush message to the server after sending the text |
| 20 | + connection.flush(); |
| 21 | + |
14 | 22 | connection.on(LiveTTSEvents.Close, () => { |
15 | | - console.log("Connection closed."); |
| 23 | + console.log("Connection closed"); |
16 | 24 | }); |
17 | 25 |
|
18 | 26 | connection.on(LiveTTSEvents.Metadata, (data) => { |
19 | | - console.log(`Deepgram Metadata: ${data}`); |
| 27 | + console.dir(data, { depth: null }); |
20 | 28 | }); |
21 | 29 |
|
22 | 30 | connection.on(LiveTTSEvents.Audio, (data) => { |
23 | | - console.log(`Deepgram Audio: ${data}`); |
| 31 | + console.log("Deepgram audio data received"); |
| 32 | + // Concatenate the audio chunks into a single buffer |
| 33 | + const buffer = Buffer.from(data); |
| 34 | + audioBuffer = Buffer.concat([audioBuffer, buffer]); |
24 | 35 | }); |
25 | 36 |
|
26 | | - connection.on(LiveTTSEvents.Flushed, (data) => { |
| 37 | + connection.on(LiveTTSEvents.Flushed, () => { |
27 | 38 | console.log("Deepgram Flushed"); |
| 39 | + // Write the buffered audio data to a file when the flush event is received |
| 40 | + writeFile(); |
28 | 41 | }); |
29 | 42 |
|
30 | 43 | connection.on(LiveTTSEvents.Error, (err) => { |
31 | 44 | console.error(err); |
32 | 45 | }); |
| 46 | + }); |
33 | 47 |
|
34 | | - fetch(url) |
35 | | - .then((r) => r.body) |
36 | | - .then((res) => { |
37 | | - res.on("readable", () => { |
38 | | - connection.send(res.read()); |
39 | | - }); |
| 48 | + const writeFile = () => { |
| 49 | + if (audioBuffer.length > 0) { |
| 50 | + fs.writeFile("output.mp3", audioBuffer, (err) => { |
| 51 | + if (err) { |
| 52 | + console.error("Error writing audio file:", err); |
| 53 | + } else { |
| 54 | + console.log("Audio file saved as output.mp3"); |
| 55 | + } |
40 | 56 | }); |
41 | | - }); |
| 57 | + audioBuffer = Buffer.alloc(0); // Reset buffer after writing |
| 58 | + } |
| 59 | + }; |
42 | 60 | }; |
43 | 61 |
|
44 | 62 | live(); |
0 commit comments