Skip to content

Commit

Permalink
🆕 add repairWavHeader helper to text to speech
Browse files Browse the repository at this point in the history
  • Loading branch information
Ammar Dodin committed Nov 29, 2017
1 parent 6a1a632 commit 0558f4e
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions text-to-speech/v1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,62 @@ class TextToSpeechV1 extends GeneratedTextToSpeechV1 {
voice(params, callback) {
return super.getVoice(params, callback);
}

/**
* Repair the WAV header of an audio/wav file.
*
* @param {Buffer} wavFileData - Wave audio - will be edited in place and returned
* @return {Buffer} wavFileData - the original Buffer, with a correct header
*/
repairWavHeader = function(wavFileData) {
const totalBytes = wavFileData.length;

// bytes 4-8 in header give the total file size,
// after the first 8 bytes
// this is a reliable constant
const chunkSize = totalBytes - 8;
wavFileData.writeInt32LE(chunkSize, 4);

// the first subchunk is at byte 12, the fmt subchunk
// this is the only other reliable constant
let chunkIdOffset = 12;
const fieldSize = 4;

// every subchunk has a 4 byte id followed by a 4 byte size field
let chunkSizeOffset = chunkIdOffset + fieldSize;
let subchunk2sizeLocation = 0;

// initialize values to hold data of each chunk we come across
let tempChunkID = '';
let tempChunkSize = 0;

while (tempChunkID !== 'data') {
if (chunkSizeOffset + fieldSize > totalBytes) {
break;
}

tempChunkID = wavFileData
.slice(chunkIdOffset, chunkIdOffset + fieldSize)
.toString('ascii');
tempChunkSize = wavFileData.readInt32LE(chunkSizeOffset);

// save the location of the data size field
if (tempChunkID === 'data') {
subchunk2sizeLocation = chunkSizeOffset;
}

// skip over all the data in the temp chunk
chunkIdOffset = chunkSizeOffset + fieldSize + tempChunkSize;
chunkSizeOffset = chunkIdOffset + fieldSize;
}

const subchunk2size = totalBytes - subchunk2sizeLocation - fieldSize;

// update the size of the audio data and return
wavFileData.writeInt32LE(subchunk2size, subchunk2sizeLocation);

return wavFileData;
};
}

export = TextToSpeechV1;

0 comments on commit 0558f4e

Please sign in to comment.