@wpdas/wave-header
v1.0.1
Published
Generates, Reads and Rewrites a WAVE-file header.
Downloads
2,063
Maintainers
Readme
wave-header
Using this module you can generate, read and rewrite a WAVE-file header. It's very useful for fix wav file headers as well.
I developed this module with a purpose to fix wav files generated by FFmpeg using stream. It's well-known that every wav files that was generated by FFmpeg in a stream has an issue with its header information, and the final file presents issue with the total time (00:00). This module will definitely fix this issue.
You can use this module for many others purposes, of course.
Examples
Generating a WAVE-file header buffer:
const fs = require('fs');
const waveHeader = require('wave-header');
const fileSize = 141971546;
// Options: (length, {channels: 1, sampleRate: 44100, bitDepth: 16})
const fileHeaderBuffer = waveHeader.generateHeader(fileSize, { bitDepth: 16 });
Reading a WAVE-file header from buffer chunk:
const { promises } = require('fs');
const waveHeader = require('wave-header');
const HEADER_OFFSET = 44;
promises
// Read only the head chunk from the audio file (better performance and reliability)
.readFile('my-wav-file.wav', { start: 0, end: HEADER_OFFSET })
.then(bufferChunk => {
const header = waveHeader.readHeader(bufferChunk);
console.log(header);
/**
{
riffHead: 'RIFF',
fileSize: 4294967295,
waveHead: 'WAVE',
fmtHead: 'fmt ',
formatLength: 16,
audioFormat: 1,
channels: 1,
sampleRate: 44100,
byteRate: 88200,
blockAlign: 2,
bitDepth: 16,
data: 'LIST',
dataLength: 130
}
*/
});
Rewriting the header of an issued audio file in real time using stream process. You can use this example when you're using FFmpeg to get wav streamed file and fix the header:
const { promises, createReadStream, createWriteStream } = require('fs');
const waveHeader = require('wave-header');
const audioFileWithHeaderIssueDir = 'my-wav-file-with-header-issue.wav';
let firstChunkRead = false;
function fixAudioHeader(fileSize) {
const newHeaderBuffer = waveHeader.generateHeader(fileSize, {
bitDepth: 16
});
// Final file with header fixed
const writeStream = createWriteStream('my-wav-file-with-fixed-header.wav');
createReadStream(audioFileWithHeaderIssueDir).on('data', buffer => {
// WARNING: Rewrites the header information in a chunk of buffer. Must be used the first chunk of buffer from a .wav file.
if (!firstChunkRead) {
writeStream.write(
waveHeader.rewriteHeaderInBufferChunk(newHeaderBuffer, buffer)
);
firstChunkRead = true;
} else {
writeStream.write(buffer);
}
});
}
promises.stat(audioFileWithHeaderIssueDir).then(stats => {
fixAudioHeader(stats.size);
});
Well to know
If you want to use similar process above with AWS.S3, you may want to use stream.PassThrough
to write the fixed buffer.