als-wave-parser
v2.3.0
Published
lightweight yet powerful solution for WAV file manipulation
Downloads
82
Readme
als-wave-parser
als-wave-parser is a comprehensive library for parsing, processing, and reconstructing WAV files. It allows you to analyze WAV files, extract audio data, split them into separate channels, merge them back into an interleaved sample stream, and even reconstruct a complete WAV file with a proper header (including format, numChannels, sampleRate, byteRate, blockAlign, bitsPerSample).
Note:
The browser bundle is generated aswav-parser.jswhile the original Node.js version is exported viaindex.js(specified as themainentry point).
📌 Features
Parse WAV files:
Read WAV files from anArrayBufferand extract detailed header information along with normalized audio data.Split Channels:
Automatically split the audio data into separate channels.Merge Channels:
Recombine channels into a single interleavedFloat32Array.Reconstruct WAV File:
Convert the parsed data (including channels) back into a complete WAV fileArrayBufferwith a correctly formatted header.Precision Matching:
All values (channels, sampleRate, etc.) are consistent with the Web Audio API (decodeAudioData).Works in both Node.js and Browser environments.
🚀 Installation
Node.js
Install via npm:
npm install als-wave-parserIn Node.js, the main module is provided in index.js.
Browser Usage
Include the browser bundle:
<script src="node_modules/als-wave-parser/wav-parser.js"></script>This script exposes WaveParser as a global variable.
📖 API
Static Methods
WaveParser.mergeChannels(channels)
Merges an array of channels (each an array of normalized samples) into a single interleaved Float32Array.
Usage:
const mergedSamples = WaveParser.mergeChannels(channels);WaveParser.splitChannels(samples, numChannels)
Splits a Float32Array of interleaved audio samples into an array of channels.
Usage:
const channels = WaveParser.splitChannels(audioData, numChannels);WaveParser.toWavBuffer({...})
Converts the parsed WAV file data (including channels) into a complete WAV file ArrayBuffer.
This function constructs the WAV header (RIFF, fmt, data chunks) and encodes the audio data according to the bit depth.
Usage (static version):
const wavBuffer = WaveParser.toWavBuffer({
numChannels,
sampleRate,
bitsPerSample,
format, // "PCM" or other string (if not PCM, AudioFormat is set to 3 for float)
byteRate,
blockAlign,
samples // Array of channels (each an array of normalized floats)
});Instance Methods and Properties
new WaveParser(arrayBuffer)
Creates a new parser object by reading the provided WAV file ArrayBuffer.
Parameters:
arrayBuffer: The content of a WAV file as anArrayBuffer.
Example:
// Node.js
const fs = require('fs');
const WaveParser = require('als-wave-parser');
const buffer = fs.readFileSync('audio.wav');
const wave = new WaveParser(buffer);
console.log(wave.sampleRate); // Sampling rate
console.log(wave.numChannels); // Number of channelsThe parser instance exposes the following properties:
wave.audioData– The raw audio data as aFloat32Array.wave.samples– An array where each element is an array of normalized samples for that channel.wave.numChannels– Number of audio channels.wave.sampleRate– Sampling rate (e.g., 44100 Hz).wave.byteRate– Byte rate as read from the header.wave.blockAlign– Block alignment (bytes per sample frame).wave.bitsPerSample– Bit depth (8, 16, or 32).wave.duration– Duration of the audio (in seconds).wave.timeInterval– Time interval between consecutive samples.
wave.mergeChannels()
Merges the separated channels (from wave.samples) back into a single interleaved Float32Array.
Returns:
A Float32Array containing the merged audio data.
Example:
const mergedSamples = wave.mergeChannels();
console.log(mergedSamples);wave.toWavBuffer()
Reconstructs a complete WAV file from the parsed data. It generates an ArrayBuffer that includes:
- The RIFF header,
- The
fmtchunk (with AudioFormat, numChannels, sampleRate, byteRate, blockAlign, bitsPerSample), - The
datachunk with interleaved PCM data.
Returns:
An ArrayBuffer representing the full WAV file.
Example:
const wavBuffer = wave.toWavBuffer();
// In a browser, to play or download:
const blob = new Blob([wavBuffer], { type: 'audio/wav' });
const url = URL.createObjectURL(blob);
const audio = new Audio(url);
audio.play();📌 Usage Examples
Node.js Example
const fs = require('fs');
const WaveParser = require('als-wave-parser');
// or
import WaveParser from 'als-wave-parser'
// Load and parse the WAV file
const buffer = fs.readFileSync('audio.wav');
const wave = new WaveParser(buffer);
// Display header information
console.log(`Sample Rate: ${wave.sampleRate} Hz`);
console.log(`Channels: ${wave.numChannels}`);
console.log(`Bit Depth: ${wave.bitsPerSample}`);
// Merge channels and reconstruct WAV file
const mergedSamples = wave.mergeChannels();
const wavBuffer = wave.toWavBuffer();
// Save the reconstructed WAV file to disk
fs.writeFileSync('reconstructed.wav', Buffer.from(wavBuffer));Browser Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>als-wave-parser Demo</title>
<script src="wav-parser.js"></script>
</head>
<body>
<input type="file" id="fileInput" accept="audio/wav">
<script>
document.getElementById('fileInput').addEventListener('change', async (event) => {
const file = event.target.files[0];
if (!file) return;
const arrayBuffer = await file.arrayBuffer();
const wave = new WaveParser(arrayBuffer);
console.log("Sample Rate:", wave.sampleRate);
console.log("Channels:", wave.numChannels);
// Reconstruct the WAV file
const wavBuffer = wave.toWavBuffer();
const blob = new Blob([wavBuffer], { type: 'audio/wav' });
const url = URL.createObjectURL(blob);
// Play the reconstructed audio
const audio = new Audio(url);
audio.play();
});
</script>
</body>
</html>Additional Notes
Supported Formats:
Currently supports PCM WAV files with 8, 16, and 32-bit depths. Support for 24-bit or compressed formats is not provided.Extra Chunks:
Only thefmtanddatachunks are processed. Other chunks (e.g., LIST, fact) are ignored.Memory Considerations:
The library creates additional arrays when splitting channels. For very large files, consider memory usage.Extensibility:
The API is designed to be extended with additional processing features (e.g., FFT-based filtering, channel effects) in future releases.
