Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

wavefile

Package Overview
Dependencies
Maintainers
1
Versions
150
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

wavefile

Read & write wave files with 4, 8, 11, 12, 16, 20, 24, 32 & 64-bit data.

  • 6.2.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
37K
increased by8.77%
Maintainers
1
Weekly downloads
 
Created
Source

wavefile

Read & write wave files with 4, 8, 11, 12, 16, 20, 24, 32 & 64-bit data.
Copyright (c) 2017-2018 Rafael da Silva Rocha.
https://github.com/rochars/wavefile

NPM version Example
Codecov Unix Build Windows Build Scrutinizer

About

wavefile is a module to work with wav files. It is partly inspired by SoX and intended to run in both Node.js and the browser.

With wavefile you can:

  • Create wav files from scratch
  • Read existing wav files
  • Encode/decode files as ADPCM, A-Law and mu-Law
  • Read/write the data in a wav file header
  • Turn RIFF files to RIFX and RIFX files to RIFF
  • Edit BWF metada ("bext" chunk)
  • Change the bit depth of the audio

And more.

wavefile is extensively tested and contains samples of all supported formats. Please note that some formats (like 8-bit A-Law and 64-bit floating point) are not widely supported and may not load in every player.

Install

npm install wavefile

See it in action

Using wavefile to extend the browser audio playing capabilities:

https://rochars.github.io/wavefile/example

Drag and drop .wav files and play them. This example uses wavefile and wavesurfer to create a browser player that supports mu-Law, A-Law, IMA ADPCM, 64-bit wav files and more.

Web browsers are typically limited to play wav files with 8, 16, 24 and 32-bit data. With wavefile you can extended this by changing the bit depth of wav files on the fly before loading them into the player:

Playing ADPCM in the browser:

// Load a wav file that is encoded as 4-bit IMA ADPCM:
let wav = new Wavefile(ADPCMFileBuffer);

// Change the bit depth to 16-bit, supported by most browsers:
wav.fromIMAADPCM();

// Get the byte buffer of your new, browser-friendly wav file:
let buffer = wav.toBuffer();

// Load your new wav file into your player
// ...

Playing a 64-bit wave file in the browser:

// Load a wav file that has 64-bit audio:
let wav = new Wavefile(buffer);

// Change the bit depth to 16-bit, supported by most browsers:
wav.toBitDepth("16");

// Get the byte buffer of your new, browser-friendly wav file:
buffer = wav.toBuffer();

// Load your new wav file into your player
// ...

With wavefile you can play A-Law, mu-Law, IMA-ADPCM and 64-bit wave files on browsers using the HTML5/JavaScript player of your choice. This example use wavesurfer.

Check out wavesurfer:
https://github.com/katspaugh/wavesurfer.js

Creating wave files in the browser:

https://tr2099.github.io/

Hit "Load in player" to generate wave files.

This website uses wavefile to create the files. The effects are provided by other libraries.

Some bit depths may not be supported by your browser, like 32-bit floating point or 64-bit floating point (WaveFile is used just to create the files, not to play them).

Use

let fs = require("fs");
let Wavefile = require("wavefile");

let wav = new Wavefile(fs.readFileSync("file.wav"));
console.log(wav.container);
console.log(wav.chunkSize);
console.log(wav.fmt.chunkId);
fs.writeFileSync(path, wav.toBuffer());

Create wave files from scratch

You must inform the number of channels, the sample rate, the bit depth and the samples (in this order). The samples should be represented as an array of numbers. The array may be multidimensional if there is more than one channel.

Mono:
let wav = new WaveFile();

// Create a mono wave file, 44.1 kHz, 32-bit and 4 samples
wav.fromScratch(1, 44100, '32', [0, -2147483648, 2147483647, 4]);
fs.writeFileSync(path, wav.toBuffer());
Stereo:

Samples can be informed interleaved or de-interleaved. If they are de-interleaved, WaveFile will interleave them. In this example they are de-interleaved.

// Stereo, 48 kHz, 8-bit, de-interleaved samples
// WaveFile interleave the samples automatically
wav.fromScratch(2, 48000, '8', [
    [0, -2, 4, 3],
    [0, -1, 4, 3]
]);
fs.writeFileSync(path, wav.toBuffer());

// Default is RIFF. To create RIFX files:
wav.fromScratch(1, 44100, '32', samples, {"container": "RIFX"});
fs.writeFileSync(path, wav.toBuffer());

Possible values for the bit depth are:
"4" - 4-bit IMA-ADPCM
"8" - 8-bit
"8a" - 8-bit A-Law
"8m" - 8-bit mu-Law
"16" - 16-bit
"24" - 24-bit
"32" - 32-bit
"32f" - 32-bit floating point
"64" - 64-bit floating point

You can also use any bit depth between "8" and "53", like "11", "12", "17", "20" and so on.

A word on bit depths

Bit depths that do not fill full bytes (like 11-bit, 21-bit and so son) are actually stored like the next greater bit depth that fill a full sequence of bytes:

  • 11-bit is stored like 16-bit (2 bytes)
  • 14-bit is stored like 16-bit (2 bytes)
  • 17-bit is stored like 24-bit (3 bytes)
  • 27-bit is stored like 32-bit (4 bytes)

So even if files like this are valid (and playable in most players), they allow their samples to be greater than the actual limit of their audio bit depth. So:

  • 11-bit files can contain 16-bit samples
  • 17-bit files can contain 24-bit samples
  • 29-bit files can contain 32-bit samples

Most players will deal with this by adjusting the level to the next greater bit depth, so most times a true 14-bit wave file will actually play like a 16-bit wave file with a low volume.

wavefile do not limit the range of the samples for those cases, so you should know what you are doing when dealing with uncommon bit depths to avoid unexpected results.

Files with sample resolution greater than 32-bit (integer) are implemented as WAVE_FORMAT_EXTENSIBLE and are unlikely to be supported by any player. They can be played in the example page:
https://rochars.github.io/wavefile/example
They are converted to 16-bit before being loaded by the player, allowing normal reproduction.

Interleave and de-interleave stereo samples

Samples in WaveFile objects are interleaved by default, even if you created the file from scratch using de-interleaved samples.

You can de-interleave them:

// De-interleave the samples into multiple channels
wav.deInterleave();

To interleave them:

// Interleave stereo samples
wav.interleave();

RIFF to RIFX and RIFX to RIFF

// Turn a RIFF file to a RIFX file
wav.toRIFX();

// Turn a RIFX file to a RIFF file
wav.toRIFF();

IMA-ADPCM

16-bit 8000 Hz mono wave files can be compressed as IMA-ADPCM:

// Encode a 16-bit wave file as 4-bit IMA-ADPCM:
wav.toIMAADPCM();

IMA-ADPCM files compressed with wavefile will have a block align of 256 bytes.

If the audio is not 16-bit it will be converted to 16-bit before compressing. Compressing audio with sample rates different from 8000 Hz or number of channels greater than 1 will throw errors.

To decode 4-bit IMA-ADPCM as 16-bit linear PCM:

// Decode 4-bit IMA-ADPCM as 16-bit:
wav.fromIMAADPCM();

Decoding always result in 16-bit audio.

A-Law

16-bit wave files (mono or stereo) can be encoded as A-Law:

// Encode a 16-bit wave file as 8-bit A-law:
wav.toALaw();

If the audio is not 16-bit it will be converted to 16-bit before compressing.

To decode 8-bit A-Law as 16-bit linear PCM:

// Decode 8-bit A-Law as 16-bit:
wav.fromALaw();

Decoding always result in 16-bit audio.

mu-Law

16-bit wave files (mono or stereo) can be encoded as mu-Law:

// Encode a 16-bit wave file as 8-bit mu-law:
wav.toMuLaw();

If the audio is not 16-bit it will be converted to 16-bit before compressing.

To decode 8-bit mu-Law as 16-bit linear PCM:

// Decode 8-bit mu-Law as 16-bit:
wav.fromMuLaw();

Decoding always result in 16-bit audio.

Change the bit depth

You can't change to and from 4-bit ADPCM, 8-bit A-Law and 8-bit mu-Law. To encode/decode files as ADPCM, A-Law and mu-Law you must use the toIMAADPCM(), fromIMAADPCM(), toALaw(), fromALaw(), toMuLaw() and fromMuLaw() methods.

// Load a wav file with 32-bit audio
let wav = new Wavefile(fs.readFileSync("32bit-file.wav"));

// Change the bit depth to 24-bit
wav.toBitDepth("24");

// Write the new 24-bit file
fs.writeFileSync("24bit-file.wav", wav.toBuffer());

// You can use any supported bit depth:
wav.toBitDepth("11");
fs.writeFileSync("11bit-file.wav", wav.toBuffer());
Change the declared bit depth without re-scaling the samples

This may be needed when dealing with files whose audio bit depths do not fill a full sequence of bytes (like 12-bit files), as those files may contain samples that outrange their declared bit depth limits and re-scaling their samples may result in clipping.

You may want to change the bit depth of those files but don't touch their samples. You can do this by setting the optional changeResolution parameter to false.

// Load a wav file that say it has 11-bit audio, but has samples
// in the 16-bit range:
let wav = new Wavefile(fs.readFileSync("11bit-file.wav"));

// Change the bit depth of the file to 16-bit without actually
// modifying the samples so the output file will have the same
// leve as the original one:
wav.toBitDepth("16", false);

// Write the new 16-bit file to disk
fs.writeFileSync("16bit-file.wav", wav.toBuffer());

Now that your samples are in the correct range you may change again to 11-bit, but this time actually scaling down the samples:

// Change the bit depth of the file to 11-bit, but now actually
// scaling down the samples to 11-bit:
wav.toBitDepth("11");

// write the new 11-bit file to disk:
fs.writeFileSync("11bit-file-new.wav", wav.toBuffer());

The changeResolution option only works when dealing with bit depths that do not fill a full sequence of bytes, both to and from. Changing to and from other bit depths will always re-scale the samples.

The properties

Since version 6.0.0 (2018-05-02) the samples are stored in data.samples.

console.log(wav.data.samples);
// Output an array of numbers

The other public properties:

let wav = new Wavefile(fs.readFileSync("file.wav"));

// The container data
console.log(wav.container); //"RIFF" or "RIFX"
console.log(wav.chunkSize);
console.log(wav.format); // WAVE

// "bext"
console.log(wav.bext.chunkId);
console.log(wav.bext.chunkSize);
// ...

// "fmt "
console.log(wav.fmt.chunkId);
console.log(wav.fmt.chunkSize);
console.log(wav.fmt.audioFormat);
console.log(wav.fmt.numChannels);
console.log(wav.fmt.sampleRate);
console.log(wav.fmt.byteRate);
console.log(wav.fmt.blockAlign);
console.log(wav.fmt.bitsPerSample);
// "fmt " extension
console.log(wav.fmt.cbSize);
console.log(wav.fmt.validBitsPerSample);
console.log(wav.fmt.dwChannelMask);
// subformat is a 128-bit GUID split into 4 32-bit values.
console.log(wav.fmt.subformat[0]); 
console.log(wav.fmt.subformat[1]); 
console.log(wav.fmt.subformat[2]);
console.log(wav.fmt.subformat[3]);

// "fact"
console.log(wav.fact.chunkId);
console.log(wav.fact.chunkSize);
console.log(wav.fact.dwSampleLength);

// "data"
console.log(wav.data.chunkId);
console.log(wav.data.chunkSize);
console.log(wav.data.samples);

// "cue "
console.log(wav.cue.chunkId);
console.log(wav.cue.chunkSize);
// ...
BWF data

BWF data ("bext" chunk) is stored in the bext property.

wav.bext = {
    "chunkId": "",
    "chunkSize": 0,
    "description": "", // 256 chars
    "originator": "", // 32 chars
    "originatorReference": "", // 32 chars
    "originationDate": "", // 10 chars
    "originationTime": "", // 8 chars
    "timeReference": [], // 2 32-bit numbers representing a 64-bit value
    "version": 0, // 16-bit number
    "UMID": "", // 64 chars
    "loudnessValue": 0, // 16-bit number
    "loudnessRange": 0, // 16-bit number
    "maxTruePeakLevel": 0, // 16-bit number
    "maxMomentaryLoudness": 0, // 16-bit number
    "maxShortTermLoudness": 0, // 16-bit number
    "reserved": "", // 180 chars
    "codingHistory": "" // string, unlimited size
};
Cue points

"cue " chunk data is stored as follows:

wav.cue = {
    "chunkId": "",
    "chunkSize": 0,
    "dwCuePoints": 0, //DWORD
    "points": [],
};

Items in cue.points are objects with this signature:

{
    "dwName": 0, //DWORD
    "dwPosition": 0, //DWORD
    "fccChunk": 0, //FOURCC,
    "dwChunkStart": 0, //DWORD,
    "dwBlockStart": 0, //DWORD,
    "dwSampleOffset": 0, //DWORD,
}
RF64

wavefile have limited support of RF64 files. Changing the bit depth or applying compression to the samples will result in a RIFF file.

this.ds64 = {
    "chunkId": "",
    "chunkSize": 0,
    "riffSizeHigh": 0,
    "riffSizeLow": 0,
    "dataSizeHigh": 0,
    "dataSizeLow": 0,
    "originationTime": 0,
    "sampleCountHigh": 0,
    "sampleCountLow": 0
};

The samples

Range:

  • 0 to 255 for 8-bit
  • -32768 to 32767 for 16-bit
  • -8388608 to 8388607 for 24-bit
  • -2147483648 to 2147483647 for 32-bit
  • -1.0 to 1.0 for 32-bit (float)
  • -1.0 to 1.0 for 64-bit (float)

LICENSE

Copyright (c) 2017-2018 Rafael da Silva Rocha.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Keywords

FAQs

Package last updated on 04 May 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc