-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
54 additions
and
52 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import { PassThrough } from "stream"; | ||
import { Readable } from "node:stream"; | ||
|
||
export function getWavHeader( | ||
audioLength: number, | ||
sampleRate: number, | ||
channelCount = 1, | ||
bitsPerSample = 16 | ||
): Buffer { | ||
const wavHeader = Buffer.alloc(44); | ||
wavHeader.write("RIFF", 0); | ||
wavHeader.writeUInt32LE(36 + audioLength, 4); // Length of entire file in bytes minus 8 | ||
wavHeader.write("WAVE", 8); | ||
wavHeader.write("fmt ", 12); | ||
wavHeader.writeUInt32LE(16, 16); // Length of format data | ||
wavHeader.writeUInt16LE(1, 20); // Type of format (1 is PCM) | ||
wavHeader.writeUInt16LE(channelCount, 22); // Number of channels | ||
wavHeader.writeUInt32LE(sampleRate, 24); // Sample rate | ||
wavHeader.writeUInt32LE((sampleRate * bitsPerSample * channelCount) / 8, 28); // Byte rate | ||
wavHeader.writeUInt16LE((bitsPerSample * channelCount) / 8, 32); // Block align ((BitsPerSample * Channels) / 8) | ||
wavHeader.writeUInt16LE(bitsPerSample, 34); // Bits per sample | ||
wavHeader.write("data", 36); // Data chunk header | ||
wavHeader.writeUInt32LE(audioLength, 40); // Data chunk size | ||
return wavHeader; | ||
} | ||
|
||
export function prependWavHeader( | ||
readable: Readable, | ||
audioLength: number, | ||
sampleRate: number, | ||
channelCount = 1, | ||
bitsPerSample = 16 | ||
): Readable { | ||
const wavHeader = getWavHeader( | ||
audioLength, | ||
sampleRate, | ||
channelCount, | ||
bitsPerSample | ||
); | ||
let pushedHeader = false; | ||
const passThrough = new PassThrough(); | ||
readable.on("data", (data) => { | ||
if (!pushedHeader) { | ||
passThrough.push(wavHeader); | ||
pushedHeader = true; | ||
} | ||
passThrough.push(data); | ||
}); | ||
readable.on("end", () => { | ||
passThrough.end(); | ||
}); | ||
return passThrough; | ||
} |