@@ -5,6 +5,36 @@ const { join } = require("path");
55
66const deepgram = createClient ( process . env . DEEPGRAM_API_KEY ) ;
77
8+ // Add WAV header generation function
9+ function createWavHeader ( audioData , sampleRate = 16000 , channels = 1 , bitsPerSample = 16 ) {
10+ const dataLength = audioData . length ;
11+ const headerLength = 44 ;
12+ const fileLength = dataLength + headerLength - 8 ;
13+
14+ const header = Buffer . alloc ( headerLength ) ;
15+
16+ // RIFF header
17+ header . write ( "RIFF" , 0 ) ;
18+ header . writeUInt32LE ( fileLength , 4 ) ;
19+ header . write ( "WAVE" , 8 ) ;
20+
21+ // fmt chunk
22+ header . write ( "fmt " , 12 ) ;
23+ header . writeUInt32LE ( 16 , 16 ) ; // fmt chunk size
24+ header . writeUInt16LE ( 1 , 20 ) ; // audio format (PCM)
25+ header . writeUInt16LE ( channels , 22 ) ; // channels
26+ header . writeUInt32LE ( sampleRate , 24 ) ; // sample rate
27+ header . writeUInt32LE ( ( sampleRate * channels * bitsPerSample ) / 8 , 28 ) ; // byte rate
28+ header . writeUInt16LE ( ( channels * bitsPerSample ) / 8 , 32 ) ; // block align
29+ header . writeUInt16LE ( bitsPerSample , 34 ) ; // bits per sample
30+
31+ // data chunk
32+ header . write ( "data" , 36 ) ;
33+ header . writeUInt32LE ( dataLength , 40 ) ;
34+
35+ return header ;
36+ }
37+
838const agent = async ( ) => {
939 let audioBuffer = Buffer . alloc ( 0 ) ;
1040 let i = 0 ;
@@ -106,7 +136,17 @@ const agent = async () => {
106136
107137 connection . on ( AgentEvents . AgentAudioDone , async ( ) => {
108138 console . log ( "Agent audio done" ) ;
109- await writeFile ( join ( __dirname , `output-${ i } .wav` ) , audioBuffer ) ;
139+
140+ // Create WAV header and combine with audio data
141+ if ( audioBuffer . length > 0 ) {
142+ const wavHeader = createWavHeader ( audioBuffer ) ;
143+ const wavFile = Buffer . concat ( [ wavHeader , audioBuffer ] ) ;
144+ await writeFile ( join ( __dirname , `output-${ i } .wav` ) , wavFile ) ;
145+ console . log ( `Wrote ${ wavFile . length } bytes to output-${ i } .wav` ) ;
146+ } else {
147+ console . log ( "No audio data to write" ) ;
148+ }
149+
110150 audioBuffer = Buffer . alloc ( 0 ) ;
111151 i ++ ;
112152 } ) ;
0 commit comments