wavefile

repository·master·Indexed 42 days ago

https://github.com/rochars/wavefile

A library for creating, reading, and writing WAV and RIFF files according to specifications. It supports Node.js, browsers (IE10+), and provides a command-line interface. Version 11.0.0 features include support for RIFF and RIFX containers, bit depth and sample rate conversion, and encoding/decoding for compressed formats such as IMA-ADPCM, A-Law, and mu-Law.

Tokens
8K
Snippets
37
Records
39
Agent score
53%

What's inside wavefile

  1. Use wavefile in the Browser

    master

    For browser environments (IE10+), you can include wavefile via a <script> tag using the file in the dist folder or via a CDN like jsDelivr or unpkg.

    <!-- Using local dist file -->
    <script src="wavefile.js"></script>
    <script>
      var wav = new wavefile.WaveFile();
    </script>
    
    <!-- Using jsDelivr CDN -->
    <script src="https://cdn.jsdelivr.net/npm/wavefile"></script>
    
    <!-- Using unpkg CDN -->
    <script src="https://unpkg.com/wavefile"></script>
  2. Use wavefile in Node.js

    master

    You can import wavefile in Node.js using CommonJS or ESM syntax. The primary class for interacting with audio files is WaveFile.

    // CommonJS option 1
    const wavefile = require('wavefile');
    let wav = new wavefile.WaveFile();
    
    // CommonJS option 2
    const WaveFile = require('wavefile').WaveFile;
    let wav = new WaveFile();
    
    // ESM option
    import { WaveFile } from 'wavefile';
    let wav = new WaveFile();
  3. Basic Node.js usage example

    master

    This example demonstrates how to load a WAV file from a buffer, inspect its properties, and export the data as a Buffer or a DataURI.

    const WaveFile = require('wavefile').WaveFile;
    
    // Load a wav file buffer as a WaveFile object
    let wav = new WaveFile(buffer);
    
    // Check some of the file properties
    console.log(wav.container);
    console.log(wav.chunkSize);
    console.log(wav.fmt.chunkId);
    
    // Call toBuffer() to get the bytes of the file.
    // You can write the output straight to disk:
    let wavBuffer = wav.toBuffer();
    
    // Call toDataURI() to get the file as a DataURI:
    let wavDataURI = wav.toDataURI();
  4. Manage RIFF tags

    master

    RIFF tags (like ICMT) can be managed using these methods:

    • setTag(tag, value): Creates or overwrites a tag.
    • getTag(tag): Returns the value of the tag if it exists.
    • deleteTag(tag): Deletes the specified tag.
    // Write the ICMT tag
    wav.setTag("ICMT", "some comments");
    
    // Get the tag
    console.log(wav.getTag("ICMT"));
    
    // Delete the tag
    wav.deleteTag("ICMT");
  5. Manage RIFF tags (INFO chunk)

    master

    You can manipulate metadata tags within the RIFF INFO chunk:

    • setTag(tag, value): Writes or overwrites a tag.
    • getTag(tag): Returns the value of a tag, or null if not found.
    • deleteTag(tag): Removes a tag. Returns true if deleted.
    • listTags(): Returns an object containing all tags in the file.
    waveFile.setTag('artist', 'John Doe');
    const artist = waveFile.getTag('artist');
    const allTags = waveFile.listTags();
  6. Change bit depth and sample rate

    master

    Change Bit Depth

    Use toBitDepth(bitDepth) to change the bit depth of the samples. No dithering is performed.

    Change Sample Rate

    Use toSampleRate(sampleRate, options) to resample the audio.

    Options:

    • method: The interpolation method. Options are:
      • "point": Nearest point (fastest, lowest quality, no LPF).
      • "linear": Linear interpolation (fast, low quality, no LPF).
      • "cubic": Cubic interpolation (default, uses LPF by default).
      • "sinc": Windowed sinc (slowest, highest quality, uses LPF by default).
    • LPF: Boolean to enable/disable the Low Pass Filter (default is true for cubic and sinc).
    • LPFType: The type of LPF to use: "IIR" (default) or "FIR".

    Note: To resample compressed files (ADPCM, mu-Law, A-Law), you must first convert them to PCM using their respective from...() methods.

    // Change bit depth to 24-bit
    wav.toBitDepth("24");
    
    // Resample to 44.1kHz using sinc interpolation with no LPF
    wav.toSampleRate(44100, {method: "sinc", LPF: false});
    
    // Resample to 44.1kHz using linear interpolation with a FIR LPF
    wav.toSampleRate(44100, {method: "linear", LPF: true, LPFType: 'FIR'});
  7. Initialize a WaveFile object

    master

    You can create a new WaveFile instance in two ways:

    1. Empty instance: Creates a blank WaveFile object.
    2. From a buffer: Creates a WaveFile object by parsing an existing .wav file buffer (Uint8Array). This will throw an error if the required RIFF, fmt , or data chunks are missing.

    Note: When using WaveFile(wav), the input must be a Uint8Array.

    // Create an empty WaveFile object
    WaveFile();
    
    // Create a WaveFile object with the contents of a wav file buffer
    WaveFile(wav);
  8. Export WaveFile to different formats

    master

    The WaveFile object can be exported into several formats for storage or web usage:

    • Buffer: toBuffer() returns a Uint8Array representing the .wav file, suitable for writing directly to disk.
    • Base64: toBase64() returns a .wav file encoded as a base64 string.
    • DataURI: toDataURI() returns a .wav file as a DataURI, which can be used directly in browser src attributes (e.g., <audio>).
    const buffer = waveFile.toBuffer();
    const base64 = waveFile.toBase64();
    const dataUri = waveFile.toDataURI();
  9. Read wave files from various sources

    master

    You can populate a WaveFile instance by reading existing data using the following methods:

    • fromBuffer(buffer): Read from a Buffer.
    • fromBase64(base64): Read from a base64 encoded string.
    • fromDataURI(dataURI): Read from a data URI.
    const WaveFile = require('wavefile').WaveFile;
    const wav = new WaveFile();
    
    wav.fromBuffer(buffer);
    wav.fromBase64(base64);
    wav.fromDataURI(dataURI);
  10. Manage Cue Points and Regions

    master

    WaveFile supports cue points and regions (defined by a start and end position).

    Creating a Cue Point: Use setCuePoint(pointData). The pointData object requires:

    • position (number): Position in milliseconds.
    • label (string, optional): A label for the point.
    • end (number, optional): The end position in milliseconds (if provided, this creates a region).

    Other Cue Point Operations:

    • listCuePoints(): Returns an array of all cue point objects.
    • updateLabel(pointIndex, label): Updates the label of a specific cue point (index starts at 1).
    • deleteCuePoint(index): Removes a cue point by its 1-based index.
    waveFile.setCuePoint({
      position: 500,
      label: 'intro',
      end: 1500
    });
    
    const points = waveFile.listCuePoints();
    waveFile.updateLabel(1, 'new label');
    waveFile.deleteCuePoint(1);
  11. Create a WaveFile from scratch

    master

    Use WaveFile.fromScratch() to build a new audio file by providing raw sample data and format specifications. This method resets any existing chunks.

    Parameters:

    • numChannels (number): Number of audio channels.
    • sampleRate (number): Sample rate (e.g., 8000, 44100, 48000, 96000, 192000).
    • bitDepth (string): Audio bit depth code. Valid values include '4', '8', '8a', '8m', '16', '24', '32', '32f', '64', or any integer string between '8' and '32' (e.g., '12').
    • samples (Array|TypedArray): The raw audio samples.
    • options (Object, optional): Use {'container': 'RIFX'} to force the container as RIFX.
    WaveFile.fromScratch(numChannels, sampleRate, bitDepth, samples, options);