### Install wavefile globally for CLI
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Install the wavefile package globally to use its command-line interface.
```bash
npm install wavefile -g
```
--------------------------------
### Install wavefile via npm
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Install the wavefile package for use in Node.js projects.
```bash
npm install wavefile
```
--------------------------------
### Browser Test Setup
Source: https://github.com/rochars/wavefile/blob/master/test/browser.html
Initializes Chai assertions, imports the WaveFile class, and configures Mocha for running tests in the browser. It also sets up Mocha to check for global leaks and starts the test runner.
```javascript
var assert = chai.assert; var WaveFile = wavefile.WaveFile; mocha.setup('bdd') //mocha.checkLeaks(); mocha.globals([ 'script*' ]).run();
```
--------------------------------
### WaveFile.listCuePoints() Example
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
This method returns a list of objects, each representing a cue point or region in the audio file. The list order reflects the order of the points in the file.
```javascript
[
{
position: 500, // the position in milliseconds
label: 'cue marker 1',
end: 1500, // the end position in milliseconds
dwName: 1,
dwPosition: 0,
fccChunk: 'data',
dwChunkStart: 0,
dwBlockStart: 0,
dwSampleOffset: 22050, // the position as a sample offset
dwSampleLength: 3646827, // the region length as a sample count
dwPurposeID: 544106354,
dwCountry: 0,
dwLanguage: 0,
dwDialect: 0,
dwCodePage: 0
},
// ...
]
```
--------------------------------
### Get All Samples
Source: https://github.com/rochars/wavefile/blob/master/README.md
Returns all samples from the wave file, packed into a Float64Array by default. Supports interleaved or de-interleaved output and custom output containers.
```javascript
WaveFile.getSamples(interleaved=false, OutputObject=Float64Array) {};
```
--------------------------------
### Get Sample by Index
Source: https://github.com/rochars/wavefile/blob/master/README.md
Retrieves a single sample from the wave file at the specified index. Throws an error if the index is out of bounds.
```javascript
WaveFile.getSample(index) {};
```
--------------------------------
### Create Regions
Source: https://github.com/rochars/wavefile/blob/master/README.md
Create regions (cue points with extra data) in audio files using the setCuePoint method. Regions are defined by a start position and an end position in milliseconds.
```APIDOC
## Create Regions
### Description
Creates regions in audio files. Regions are cue points that can have additional data associated with them.
### Method
`WaveFile.setCuePoint(cuePointObject)`
### Parameters
#### Cue Point Object
- **position** (number) - Required - The start position of the cue point in milliseconds.
- **end** (number) - Required - The end position of the region in milliseconds. Must be greater than `position`.
- **label** (string) - Optional - A label for the region.
- **dwPurposeID** (number) - Optional - Purpose ID for the cue point.
- **dwCountry** (number) - Optional - Country code for the cue point.
- **dwLanguage** (number) - Optional - Language code for the cue point.
- **dwDialect** (number) - Optional - Dialect code for the cue point.
- **dwCodePage** (number) - Optional - Code page for the cue point.
### Request Example
```javascript
wav.setCuePoint({position: 1500, end: 2500, label: 'some label'});
```
```
--------------------------------
### Sample Loop Object Structure
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Defines the structure for sample loop objects within the '_smpl.loops' array. Each object specifies loop start, end, type, and play count.
```javascript
{
/** @type {string} */
dwName: '', // a cue point ID
/** @type {number} */
dwType: 0,
/** @type {number} */
dwStart: 0,
/** @type {number} */
dwEnd: 0,
/** @type {number} */
dwFraction: 0,
/** @type {number} */
dwPlayCount: 0
}
```
--------------------------------
### Show Help Page
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Displays the help information for the wavefile command-line tool, listing all available options and their usage.
```bash
$ wavefile --help
```
--------------------------------
### Create and Manipulate WaveFile Samples
Source: https://github.com/rochars/wavefile/blob/master/README.md
Demonstrates creating a WaveFile from scratch using provided samples and then accessing and modifying individual samples using getSample() and setSample().
```javascript
wav = new WaveFile();
// some samples
let samples = [561, 1200, 423];
// Create a WaveFile using the samples
wav.fromScratch(1, 8000, "16", samples);
// Getting and setting a sample in the WaveFile instance:
wav.getSample(1); // return 1200, the value of the second sample
wav.setSample(1, 10); // change the second sample to 10
wav.getSample(1); // return 10, the new value of the second sample
```
--------------------------------
### Build wavefile Project
Source: https://github.com/rochars/wavefile/blob/master/BUILDING.md
Run this command to lint, test, compile, and generate documentation for the wavefile project.
```bash
npm run build
```
--------------------------------
### Initialize New WAV File in WaveFileCreator
Source: https://github.com/rochars/wavefile/blob/master/docs/lib_wavefile-creator.js.html
Sets up a new WAV file based on provided parameters including channel count, sample rate, bit depth, samples, and container options. It handles sample interleaving and data packing.
```javascript
newWavFile_(numChannels, sampleRate, bitDepthCode, samples, options) {
if (!options.container) {
options.container = 'RIFF';
}
this.container = options.container;
this.bitDepth = bitDepthCode;
samples = interleave(samples);
this.updateDataType_();
/** @type {number} */
let numBytes = this.dataType.bits / 8;
this.data.samples = new Uint8Array(samples.length * numBytes);
packArrayTo(samples, this.dataType, this.data.samples, 0, true);
this.makeWavHeader_(
bitDepthCode, numChannels, sampleRate,
numBytes, this.data.samples.length, options);
this.data.chunkId = 'data';
this.data.chunkSize = this.data.samples.length;
this.validateWavHeader_();
}
```
--------------------------------
### Get Audio Samples as Float64Array
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Retrieves audio samples from a WaveFile instance. By default, samples are returned de-interleaved. Set the optional boolean parameter 'interleaved' to true to get interleaved samples. You can also specify a typed array constructor for the output.
```javascript
let samples = wav.getSamples();
```
```javascript
samples = wav.getSamples(false);
```
```javascript
samples = wav.getSamples(true);
```
```javascript
samples = wav.getSamples(false, Int32Array);
```
```javascript
let samples = getSamples(false, Int16Array);
```
```javascript
let samples = getSamples(true, Int16Array);
```
--------------------------------
### Get _PMX Chunk
Source: https://github.com/rochars/wavefile/blob/master/README.md
Retrieves the content of the _PMX chunk from the wave file as a string.
```javascript
WaveFile.get_PMX() {};
```
--------------------------------
### WaveFile Object Creation
Source: https://github.com/rochars/wavefile/blob/master/README.md
Demonstrates how to instantiate a WaveFile object, either empty or from a WAV file buffer.
```APIDOC
## WaveFile Object Creation
### Description
Instantiate a WaveFile object. It can be created empty or initialized with the contents of a WAV file buffer.
### Usage
```javascript
// Create a empty WaveFile object
WaveFile();
// Create a WaveFile object with the contents of a wav file buffer
WaveFile(wav);
```
### Parameters
#### Constructor Parameters
- **wav** (Uint8Array, optional) - A wave file buffer. Throws an error if essential chunks ('RIFF', 'fmt ', 'data') are missing.
```
--------------------------------
### Get iXML Chunk
Source: https://github.com/rochars/wavefile/blob/master/README.md
Retrieves the content of the iXML chunk from the wave file as a string.
```javascript
WaveFile.getiXML() {};
```
--------------------------------
### Create WaveFile from Scratch
Source: https://github.com/rochars/wavefile/blob/master/README.md
Initialize a WaveFileCreator object with audio parameters and samples. Existing chunks are reset.
```javascript
WaveFile.fromScratch(numChannels, sampleRate, bitDepth, samples, options) {}
```
--------------------------------
### Get RIFF Tag
Source: https://github.com/rochars/wavefile/blob/master/README.md
Retrieves the value of a specified RIFF tag if it exists in the file.
```javascript
console.log(wav.getTag("ICMT"));
// some comments
```
--------------------------------
### Initialize WaveFile with ES Modules
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Import and instantiate the WaveFile class using ES module syntax.
```javascript
import { WaveFile } from 'wavefile';
let wav = new WaveFile();
```
--------------------------------
### Handle XML Chunks
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Provides methods to get and set iXML and _PMX XML chunks within a WaveFile.
```APIDOC
## XML Chunks
### Description
Supports reading and writing of iXML and _PMX chunks in WaveFile objects. The chunk data must be provided as a string.
### Method
`wav.getiXML()`
`wav.get_PMX()`
`wav.setiXML(xmlString)`
`wav.set_PMX(xmlString)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
For `setiXML` and `set_PMX`, the request body is a string containing the XML data.
### Request Example
```javascript
// Load a wav file
let wav = new WaveFile(fs.readFileSync("input.wav"));
// Get existing XML data
/** @type {string} */
let iXMLValue = wav.getiXML();
/** @type {string} */
let _PMXValue = wav.get_PMX();
// Set new XML data
wav.setiXML("Some content");
wav.set_PMX("<_PMXData>More content");
// Write the file with updated XML chunks
fs.writeFileSync("output-with-xml.wav", wav.toBuffer());
```
### Response
#### Success Response
- **getiXML() / get_PMX()**: (string) - Returns the content of the respective XML chunk, or an empty string if not present.
- **setiXML() / set_PMX()**: (void) - Modifies the WaveFile object in place. The chunk size is adjusted when `toBuffer()` is called.
#### Response Example
```json
// Example response from getiXML() or get_PMX()
"data"
```
```
--------------------------------
### WaveFile Constructor
Source: https://github.com/rochars/wavefile/blob/master/docs/index.js.html
Initializes a new WaveFile instance. Optionally loads WAV data from a buffer.
```APIDOC
## new WaveFile(wav)
### Description
Initializes a new WaveFile instance. Optionally loads WAV data from a buffer.
### Parameters
#### Path Parameters
- **wav** (Uint8Array) - Optional - A wave file buffer to load upon initialization.
### Throws
- Error: If container is not RIFF, RIFX or RF64.
- Error: If format is not WAVE.
- Error: If no 'fmt ' chunk is found.
- Error: If no 'data' chunk is found.
```
--------------------------------
### Get _PMX Chunk Data
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Retrieve the content of a _PMX chunk from a WAV file. The returned value is expected to be a string.
```javascript
/** @type {string} */
let _PMXValue = wav.get_PMX();
```
--------------------------------
### Get iXML Chunk Data
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Retrieve the content of an iXML chunk from a WAV file. The returned value is expected to be a string.
```javascript
/** @type {string} */
let iXMLValue = wav.getiXML();
```
--------------------------------
### View command line options
Source: https://github.com/rochars/wavefile/blob/master/README.md
Display the available command-line options for the wavefile tool. This helps in understanding the different functionalities accessible via the CLI.
```bash
wavefile --help
```
--------------------------------
### Create Mono Wave File from Scratch
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Create a mono wave file with specified channels, sample rate, bit depth, and samples using the fromScratch method. The output buffer can be written to a file.
```javascript
let wav = new WaveFile();
// Create a mono wave file, 44.1 kHz, 32-bit and 4 samples
wav.fromScratch(1, 44100, '32', [0, -2147483, 2147483, 4]);
fs.writeFileSync(path, wav.toBuffer());
```
--------------------------------
### Get RIFF Tag Value
Source: https://github.com/rochars/wavefile/blob/master/README.md
Retrieves the value of a specified RIFF tag from the INFO chunk. Returns null if the tag is not found.
```javascript
WaveFile.getTag(tag) {}
```
--------------------------------
### fromScratch
Source: https://github.com/rochars/wavefile/blob/master/docs/lib_wavefile-creator.js.html
Initializes a new WAV file with specified parameters. Existing chunks are reset before creation.
```APIDOC
## fromScratch
### Description
Initializes a new WAV file with specified parameters. Existing chunks are reset before creation.
### Method
`fromScratch(numChannels, sampleRate, bitDepthCode, samples, options)`
### Parameters
#### Path Parameters
- **numChannels** (number) - Required - The number of channels.
- **sampleRate** (number) - Required - The sample rate (e.g., 8000, 44100, 48000, 96000, 192000).
- **bitDepthCode** (string) - Required - The audio bit depth code (e.g., '4', '8', '8a', '8m', '16', '24', '32', '32f', '64', or values between '8' and '32').
- **samples** (Array|TypedArray) - Required - The audio samples.
- **options** (Object) - Optional - Used to force the container, e.g., `{'container': 'RIFX'}`.
### Throws
- `Error` - If any argument does not meet the criteria.
```
--------------------------------
### Get All Cue Points
Source: https://github.com/rochars/wavefile/blob/master/docs/lib_wavefile-cue-editor.js.html
Retrieves all cue points from the wave file in their original order. It processes chunk data to associate labels and other metadata with each cue point.
```javascript
/**
* Return an array with all cue points in the file, in the order they appear
* in the file.
* @return {!Array}
* @private
*/
getCuePoints_() {
/** @type {!Array} */
let points = [];
for (let i = 0; i < this.cue.points.length; i++) {
/** @type {!Object} */
let chunk = this.cue.points[i];
/** @type {!Object} */
let pointData = this.getDataForCuePoint_(chunk.dwName);
pointData.label = pointData.value ? pointData.value : '';
pointData.dwPosition = chunk.dwPosition;
pointData.fccChunk = chunk.fccChunk;
pointData.dwChunkStart = chunk.dwChunkStart;
pointData.dwBlockStart = chunk.dwBlockStart;
pointData.dwSampleOffset = chunk.dwSampleOffset;
points.push(pointData);
}
return points;
}
```
--------------------------------
### fromBuffer
Source: https://github.com/rochars/wavefile/blob/master/docs/module-wavefile.WaveFile.html
Sets up the WaveFileParser object from a byte buffer. Can optionally load samples.
```APIDOC
## fromBuffer(wavBuffer, samples)
### Description
Set up the WaveFileParser object from a byte buffer.
### Method
`fromBuffer`
### Parameters
#### Path Parameters
- **wavBuffer** (Uint8Array) - Required - The buffer.
- **samples** (boolean) - Optional - True if the samples should be loaded. Defaults to `true`.
### Throws
- If container is not RIFF, RIFX or RF64.
Type: Error
- If format is not WAVE.
Type: Error
- If no 'fmt ' chunk is found.
Type: Error
- If no 'data' chunk is found.
Type: Error
```
--------------------------------
### WaveFile.fromScratch
Source: https://github.com/rochars/wavefile/blob/master/README.md
Creates a WaveFile object from scratch with specified audio parameters and samples.
```APIDOC
## WaveFile.fromScratch
### Description
Sets up the WaveFileCreator object based on the provided arguments. Existing chunks are reset.
### Method
`WaveFile.fromScratch(numChannels, sampleRate, bitDepth, samples, options)`
### Parameters
#### Path Parameters
- **numChannels** (number) - Required - The number of audio channels.
- **sampleRate** (number) - Required - The sample rate (e.g., 8000, 44100, 48000, 96000, 192000).
- **bitDepth** (string) - Required - The audio bit depth code (e.g., '4', '8', '8a', '8m', '16', '24', '32', '32f', '64', or values between '8' and '32').
- **samples** (Array|TypedArray) - Required - The audio samples.
- **options** (Object, optional) - Used to force the container as RIFX with `{'container': 'RIFX'}`.
### Throws
- Error if any argument does not meet the criteria.
```
--------------------------------
### Add, Get, and Delete RIFF Tags
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Manage RIFF tags in a wave file using setTag, getTag, and deleteTag methods. Tags are key-value pairs used for metadata.
```javascript
// Write the ICMT tag with some comments to the file
wav.setTag("ICMT", "some comments");
console.log(wav.getTag("ICMT"));
// some comments
wav.deleteTag("ICMT");
```
--------------------------------
### Get Cue Point Data
Source: https://github.com/rochars/wavefile/blob/master/docs/lib_wavefile-cue-editor.js.html
Fetches the associated data for a specific cue point using its ID. It checks for an 'adtl' LIST chunk and extracts relevant information if found.
```javascript
/**
* Return the associated data of a cue point.
* @param {number} pointDwName The ID of the cue point.
* @return {!Object}
* @private
*/
getDataForCuePoint_(pointDwName) {
/** @type {?number} */
let LISTindex = this.getLISTIndex('adtl');
/** @type {!Object} */
let pointData = {};
// If there is a adtl LIST in the file, look for
// LIST subchunks with data referencing this point
if (LISTindex !== null) {
this.getCueDataFromLIST_(pointData, LISTindex, pointDwName);
}
return pointData;
}
```
--------------------------------
### WaveFile.fromBuffer
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Sets up the WaveFileParser object from a byte buffer.
```APIDOC
## WaveFile.fromBuffer
### Description
Sets up the WaveFileParser object from a byte buffer.
### Method Signature
WaveFile.fromBuffer(bytes, samples)
### Parameters
* **bytes** (Uint8Array) - The buffer containing the WAV file data.
* **samples** (boolean, optional, defaults to true) - True if the samples should be loaded.
### Throws
* Error: If container is not RIFF, RIFX or RF64.
* Error: If format is not WAVE.
* Error: If no 'fmt ' chunk is found.
* Error: If no 'data' chunk is found.
```
--------------------------------
### Create wave files from scratch
Source: https://github.com/rochars/wavefile/blob/master/README.md
Creates a new WAV file from scratch with specified channel count, sample rate, bit depth, and sample data. Supports mono and stereo configurations, with flexible bit depth options.
```APIDOC
## fromScratch(numChannels, sampleRate, bitDepth, samples)
### Description
Creates a new WAV file from scratch with the specified parameters.
### Method
`WaveFile.fromScratch()`
### Parameters
- **numChannels** (number) - Required - The number of audio channels (e.g., 1 for mono, 2 for stereo).
- **sampleRate** (number) - Required - The sample rate of the audio in Hz (e.g., 44100, 48000).
- **bitDepth** (string) - Required - The bit depth of the audio. Possible values include "4", "8", "8a", "8m", "16", "24", "32", "32f", "64", or any integer between "8" and "53".
- **samples** (array) - Required - An array of sample data. For mono, it's a flat array. For stereo, it can be an array of arrays (de-interleaved) or a flat interleaved array.
### Request Example
```javascript
// Mono example
let wav = new WaveFile();
wav.fromScratch(1, 44100, '32', [0, -2147483, 2147483, 4]);
// Stereo example (de-interleaved)
wav.fromScratch(2, 48000, '8', [
[0, 2, 4, 3],
[0, 1, 4, 3]
]);
```
### Response
This method modifies the `WaveFile` instance in place and does not return a value directly. The WAV data can be obtained using `toBuffer()`.
```
--------------------------------
### Create WaveFile from Buffer
Source: https://github.com/rochars/wavefile/blob/master/README.md
Set up a WaveFileParser object from a byte buffer. This method validates the container and format, and loads samples if specified.
```javascript
WaveFile.fromBuffer(bytes, samples=true) {}
```
--------------------------------
### Get Audio Samples
Source: https://github.com/rochars/wavefile/blob/master/README.md
Retrieve audio samples from a WaveFile instance. By default, samples are returned de-interleaved as Float64Array. Can be configured to return interleaved samples or use different typed arrays.
```javascript
let samples = wav.getSamples();
```
```javascript
// Both will return de-interleaved samples
samples = wav.getSamples();
samples = wav.getSamples(false);
// To get interleaved samples
samples = wav.getSamples(true);
```
```javascript
// Will return the samples de-interleaved,
// packed in a array of Int32Array objects, one for each channel
samples = wav.getSamples(false, Int32Array);
// will return the samples de-interleaved,
// packed in a array of Int16Array objects, one for each channel
let samples = getSamples(false, Int16Array);
// will return the samples interleaved, packed in a Int16Array
let samples = getSamples(true, Int16Array);
```
--------------------------------
### WaveFile.fromScratch
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Creates a WaveFile object from scratch with specified audio parameters.
```APIDOC
## WaveFile.fromScratch
### Description
Creates a WaveFile object from scratch with specified audio parameters.
### Method Signature
WaveFile.fromScratch(numChannels, sampleRate, bitDepth, samples, options)
### Parameters
* **numChannels** (number) - The number of audio channels.
* **sampleRate** (number) - The audio sample rate.
* **bitDepth** (string) - The audio bit depth code. One of '4', '8', '8a', '8m', '16', '24', '32', '32f', '64' or any value between '8' and '32' (like '12').
* **samples** (Array|TypedArray) - The audio samples.
* **options** (Object, optional) - Used to force the container as RIFX with {'container': 'RIFX'}.
### Throws
* Error: If any argument does not meet the criteria.
```
--------------------------------
### Get Index of LIST Chunk by Type
Source: https://github.com/rochars/wavefile/blob/master/docs/lib_wavefile-tag-editor.js.html
Finds and returns the index of a LIST chunk based on its type (e.g., 'adtl', 'INFO'). This is an internal helper function used to locate specific chunk structures.
```javascript
getLISTIndex(listType) {
for (let i = 0, len = this.LIST.length; i < len; i++) {
if (this.LIST[i].format == listType) {
return i;
}
}
return null;
}
```
--------------------------------
### Initialize WaveFile in Node.js (CommonJS)
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Import and instantiate the WaveFile class using require in a Node.js environment.
```javascript
const wavefile = require('wavefile');
let wav = new wavefile.WaveFile();
```
--------------------------------
### Get and Set Individual Samples
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Accesses or modifies a specific sample within the WaveFile instance using its index in the sample array. Integer samples are clamped on overflow, while floating-point samples may be defined out of range.
```javascript
wav.getSample(1); // return 1200, the value of the second sample
wav.setSample(1, 10); // change the second sample to 10
wav.getSample(1); // return 10, the new value of the second sample
```
--------------------------------
### List All Tags
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Prints all available tags and their values present in the audio file.
```bash
$ wavefile input.wav --list-tags
```
--------------------------------
### Get Index of Tag within INFO Chunk
Source: https://github.com/rochars/wavefile/blob/master/docs/lib_wavefile-tag-editor.js.html
Locates the index of a specific RIFF tag within the INFO chunk. It returns an object containing the index of the INFO list and the index of the tag within that list. This is a private helper method.
```javascript
getTagIndex_(tag) {
/** @type {!Object} */
let index = {LIST: null, TAG: null};
for (let i = 0, len = this.LIST.length; i < len; i++) {
if (this.LIST[i].format == 'INFO') {
index.LIST = i;
for (let j=0, subLen = this.LIST[i].subChunks.length; j < subLen; j++) {
if (this.LIST[i].subChunks[j].chunkId == tag) {
index.TAG = j;
break;
}
}
break;
}
}
return index;
}
```
--------------------------------
### Create Stereo Wave File from Scratch
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Create a stereo wave file from scratch, providing de-interleaved samples. WaveFile will automatically interleave them. Supports various bit depths.
```javascript
// 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());
```
--------------------------------
### WaveFile Constructor
Source: https://github.com/rochars/wavefile/blob/master/docs/index.js.html
Initializes a new WaveFile object. Optionally loads a WAV file from a buffer upon instantiation.
```javascript
import { WaveFile } from 'wavefile';
// Create a new WaveFile object without loading any data
const wf = new WaveFile();
// Load a WAV file from a buffer
// const wavBuffer = new Uint8Array(...);
// const wf = new WaveFile(wavBuffer);
```
--------------------------------
### Initialize WaveFileCreator
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Sets up the WaveFileCreator object with the specified number of channels, sample rate, and bit depth. This action resets any existing chunks within the object.
```javascript
/**
* Set up the WaveFileCreator object based on the arguments passed.
* Existing chunks are reset.
* @param {number} numChannels The number of channels.
* @param {number} sampleRate The sample rate.
* Integers like 8000, 44100, 48000, 96000, 192000.
*/
WaveFile.prototype.fromScratch = function(numChannels, sampleRate, bitDepth, samples) {
// ... implementation details ...
};
```
--------------------------------
### List All Cue Points
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Displays all cue points defined within the audio file.
```bash
$ wavefile input.wav --list-cue
```
--------------------------------
### Create WaveFile from Scratch with Samples
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Initializes a WaveFile instance with specified channel count, sample rate, bit depth, and an array of samples. This method resets any existing chunks in the WaveFile object.
```javascript
wav = new WaveFile();
// some samples
let samples = [561, 1200, 423];
// Create a WaveFile using the samples
wav.fromScratch(1, 8000, "16", samples);
```
--------------------------------
### Create Cue Point
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Use WaveFile.setCuePoint() to create a cue point at a specific position in milliseconds.
```javascript
wav.setCuePoint({position: 1500});
```
--------------------------------
### Initialize WaveFile in Node.js (CommonJS - Destructuring)
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Import and instantiate the WaveFile class by destructuring from the require statement in Node.js.
```javascript
const WaveFile = require('wavefile').WaveFile;
let wav = new WaveFile();
```
--------------------------------
### fromBuffer
Source: https://github.com/rochars/wavefile/blob/master/docs/lib_wavefile-creator.js.html
Sets up the WaveFileParser object from a byte buffer. Parses the buffer to extract WAV file information.
```APIDOC
## fromBuffer
### Description
Sets up the WaveFileParser object from a byte buffer. Parses the buffer to extract WAV file information.
### Method
`fromBuffer(wavBuffer, samples)`
### Parameters
#### Path Parameters
- **wavBuffer** (Uint8Array) - Required - The buffer containing the WAV file data.
- **samples** (boolean) - Optional - Defaults to `true`. If `true`, the samples should be loaded.
### Throws
- `Error` - If container is not RIFF, RIFX or RF64.
- `Error` - If format is not WAVE.
- `Error` - If no 'fmt ' chunk is found.
- `Error` - If no 'data' chunk is found.
```
--------------------------------
### Create WaveFile Object
Source: https://github.com/rochars/wavefile/blob/master/README.md
Instantiate a WaveFile object. It can be created empty, or initialized with the contents of a WAV file buffer.
```javascript
// Create a empty WaveFile object
WaveFile();
// Create a WaveFile object with the contents of a wav file buffer
WaveFile(wav);
/**
* @param {Uint8Array=} wav A wave file buffer.
* @throws {Error} If no "RIFF" chunk is found.
* @throws {Error} If no "fmt " chunk is found.
* @throws {Error} If no "data" chunk is found.
*/
WaveFile(wav);
```
--------------------------------
### Create WaveFile from Buffer
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Initializes a WaveFile object with the content of a provided WAV file buffer. This constructor will throw errors if essential chunks like 'RIFF', 'fmt ', or 'data' are missing.
```javascript
// Create a WaveFile object with the contents of a wav file buffer
WaveFile(wav);
```
--------------------------------
### toRIFX()
Source: https://github.com/rochars/wavefile/blob/master/docs/module-wavefile.WaveFile.html
Forces the wave file to be formatted as RIFX.
```APIDOC
## toRIFX()
### Description
Force a file as RIFX.
### Method
GET
```
--------------------------------
### Load wavefile from unpkg CDN
Source: https://github.com/rochars/wavefile/blob/master/README.md
Load the wavefile library directly from the unpkg CDN. This provides access to the latest version of the library.
```html
```
--------------------------------
### Create Cue Point in Wave File
Source: https://github.com/rochars/wavefile/blob/master/docs/lib_wavefile-cue-editor.js.html
Creates a cue point in the wave file. Requires at least a position in milliseconds. Optional attributes include label, end time for regions, and various metadata like dwPurposeID, dwCountry, etc.
```javascript
setCuePoint(pointData) {
this.cue.chunkId = 'cue ';
// label attr should always exist
if (!pointData.label) {
pointData.label = '';
}
/**
* Load the existing points before erasing
* the LIST 'adtl' chunk and the cue attr
* @type {!Array}
*/
let existingPoints = this.getCuePoints_();
// Clear any LIST labeled 'adtl'
// The LIST chunk should be re-written
// after the new cue point is created
this.clearLISTadtl_();
// Erase this.cue so it can be re-written
// after the point is added
this.cue.points = [];
/**
* Cue position param is informed in milliseconds,
* here its value is converted to the sample offset
* @type {number}
*/
pointData.dwSampleOffset =
(pointData.position * this.fmt.sampleRate) / 1000;
/**
* end param is informed in milliseconds, counting
* from the start of the file.
* here its value is converted to the sample length
* of the region.
* @type {number}
*/
pointData.dwSampleLength = 0;
if (pointData.end) {
pointData.dwSampleLength =
((pointData.end * this.fmt.sampleRate) / 1000) -
pointData.dwSampleOffset;
}
// If there were no cue points in the file,
// insert the new cue point as the first
if (existingPoints.length === 0) {
this.setCuePoint_(pointData, 1);
// If the file already had cue points, This new one
// must be added in the list according to its position.
} else {
this.setCuePointInOrder_(existingPoints, pointData);
}
this.cue.dwCuePoints = this.cue.points.length;
}
```
--------------------------------
### fromScratch
Source: https://github.com/rochars/wavefile/blob/master/docs/module-wavefile.WaveFile.html
Creates a WaveFileCreator object with specified audio properties. Resets existing chunks.
```APIDOC
## fromScratch(numChannels, sampleRate, bitDepthCode, samples, options)
### Description
Set up the WaveFileCreator object based on the arguments passed. Existing chunks are reset.
### Method
`fromScratch`
### Parameters
#### Path Parameters
- **numChannels** (number) - Required - The number of channels.
- **sampleRate** (number) - Required - The sample rate. Integers like 8000, 44100, 48000, 96000, 192000.
- **bitDepthCode** (string) - Required - The audio bit depth code. One of '4', '8', '8a', '8m', '16', '24', '32', '32f', '64' or any value between '8' and '32' (like '12').
- **samples** (Array | TypedArray) - Required - The samples.
- **options** (Object) - Optional - Used to force the container as RIFX with {'container': 'RIFX'}.
### Throws
- If any argument does not meet the criteria.
Type: Error
```
--------------------------------
### Create RIFX File
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Create a new audio file with the RIFX container format by specifying 'RIFX' in the options.
```javascript
wav.fromScratch(1, 48000, '16', [0, 1, -3278, 327], {"container": "RIFX"});
```
--------------------------------
### Run Tests
Source: https://github.com/rochars/wavefile/blob/master/CONTRIBUTING.md
Execute the project's test suite to ensure code quality and identify regressions.
```bash
npm test
```
--------------------------------
### getSample
Source: https://github.com/rochars/wavefile/blob/master/docs/lib_wavefile-creator.js.html
Returns the audio sample at a specific index.
```APIDOC
## getSample
### Description
Returns the audio sample at a specific index.
### Method
`getSample(index)`
### Parameters
#### Path Parameters
- **index** (number) - Required - The sample index.
### Returns
- `number` - The sample value at the specified index.
### Throws
- `Error` - If the sample index is out of range.
```
--------------------------------
### Initialize WaveFileCreator from Existing Data
Source: https://github.com/rochars/wavefile/blob/master/docs/lib_wavefile-converter.js.html
Resets and sets up the WaveFileCreator object using existing wave file parameters. It specifically resets the fmt, fact, ds64, and data chunks.
```javascript
/**
* Set up the WaveFileCreator object based on the arguments passed.
* This method only reset the fmt , fact, ds64 and data chunks.
* @param {number} numChannels The number of channels
* (Integer numbers: 1 for mono, 2 stereo and so on).
* @param {number} sampleRate The sample rate.
* Integer numbers like 8000, 44100, 48000, 96000, 192000.
* @param {string} bitDepthCode The audio bit depth code.
* One of '4', '8', '8a', '8m', '16', '24', '32', '32f', '64'
* or any value between '8' and '32' (like '12').
* @param {!(Array|TypedArray)} samples
* The samples. Must be in the correct range according to the bit depth.
* @param {Object} options Used to define the container. Uses RIFF by default.
* @throws {Error} If any argument does not meet the criteria.
* @private
*/
fromExisting_(numChannels, sampleRate, bitDepthCode, samples, options) {
/** @type {!Object} */
let tmpWav = new WaveFileCueEditor();
Object.assign(this.fmt, tmpWav.fmt);
Object.assign(this.fact, tmpWav.fact);
Object.assign(this.ds64, tmpWav.ds64);
Object.assign(this.data, tmpWav.data);
this.newWavFile_(numChannels, sampleRate, bitDepthCode, samples, options);
}
}
/**
* Return the size in bytes of the output sample array when applying
* compression to 16-bit samples.
* @return {number}
* @private
*/
function outputSize_(byteLen, byteOffset) {
/** @type {number} */
let outputSize = byteLen / byteOffset;
if (outputSize % 2) {
outputSize++;
}
return outputSize;
}
```
--------------------------------
### Load wavefile from jsDelivr CDN
Source: https://github.com/rochars/wavefile/blob/master/README.md
Load the wavefile library directly from the jsDelivr Content Delivery Network. This is useful for quick testing or when you don't want to bundle the library.
```html
```
--------------------------------
### getSamples(interleavedopt, OutputObjectopt)
Source: https://github.com/rochars/wavefile/blob/master/docs/module-wavefile.WaveFile.html
Retrieves all audio samples from the wave file, returning them as a Float64Array. Supports options for interleaved or de-interleaved output and custom sample containers.
```APIDOC
## getSamples(interleavedopt, OutputObjectopt)
### Description
Return the samples packed in a Float64Array.
### Method
(Not specified, likely internal or utility)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **interleaved** (boolean) - Optional - True to return interleaved samples, false to return the samples de-interleaved.
- **OutputObject** (function) - Optional - The sample container, defaults to Float64Array.
### Returns
- **Array | TypedArray** - The array of samples.
```
--------------------------------
### Print Sample Rate
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Outputs the sample rate of the audio file.
```bash
$ wavefile input.wav --rate
```
--------------------------------
### WaveFile.toRIFX
Source: https://github.com/rochars/wavefile/blob/master/README.md
Forces the output file format to be RIFX.
```APIDOC
## WaveFile.toRIFX
### Description
Forces the output file to be in RIFX format.
### Method
`WaveFile.toRIFX()`
```
--------------------------------
### Convert WaveFile to Buffer
Source: https://github.com/rochars/wavefile/blob/master/README.md
Generate a byte buffer representing the WaveFile object as a .wav file, suitable for direct disk writing.
```javascript
WaveFile.toBuffer() {}
```
--------------------------------
### List All Cue Points
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Retrieve a list of all cue points in the file, ordered by their appearance, using WaveFile.listCuePoints().
```javascript
let cuePoints = wav.listCuePoints();
```
```json
[
{
position: 500, // the position in milliseconds
label: 'cue marker 1',
end: 1500, // the end position in milliseconds
dwName: 1,
dwPosition: 0,
fccChunk: 'data',
dwChunkStart: 0,
dwBlockStart: 0,
dwSampleOffset: 22050, // the position as a sample offset
dwSampleLength: 3646827, // the region length as a sample count
dwPurposeID: 544106354,
dwCountry: 0,
dwLanguage: 0,
dwDialect: 0,
dwCodePage: 0,
},
//...
];
```
--------------------------------
### Include wavefile.js in Browser
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Include the wavefile.js file in your HTML to use it in the browser. Alternatively, load it from a CDN like jsDelivr or unpkg.
```html
```
```html
```
```html
```
--------------------------------
### Create Empty WaveFile Object
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
Instantiates a new, empty WaveFile object.
```javascript
// Create a empty WaveFile object
WaveFile();
```
--------------------------------
### WaveFile Class Methods
Source: https://github.com/rochars/wavefile/blob/master/docs/index.html
The WaveFile class provides a comprehensive set of methods for working with WAV audio files. These methods allow for file creation, data manipulation, encoding/decoding, and metadata management.
```APIDOC
## WaveFile Class Methods
This document outlines the methods available on the `WaveFile` class for manipulating WAV audio files.
### Methods
* **`deleteCuePoint(id)`**: Deletes a cue point by its ID.
* **`deleteTag(id)`**: Deletes a tag by its ID.
* **`fromALaw(buffer)`**: Creates a WaveFile instance from an ALaw encoded buffer.
* **`fromBase64(base64String)`**: Creates a WaveFile instance from a Base64 encoded string.
* **`fromBuffer(buffer)`**: Creates a WaveFile instance from an ArrayBuffer or Buffer.
* **`fromDataURI(dataURI)`**: Creates a WaveFile instance from a Data URI.
* **`fromIMAADPCM(buffer)`**: Creates a WaveFile instance from an IMA ADPCM encoded buffer.
* **`fromMuLaw(buffer)`**: Creates a WaveFile instance from a MuLaw encoded buffer.
* **`fromScratch(options)`**: Creates a new WaveFile instance from scratch with specified options.
* **`get_PMX()`**: Retrieves the PMX chunk data.
* **`getiXML()`**: Retrieves the iXML chunk data.
* **`getLISTIndex(id)`**: Retrieves the index of a LIST chunk by its ID.
* **`getSample(channel, sampleIndex)`**: Retrieves a specific sample from a given channel and sample index.
* **`getSamples(channel)`**: Retrieves all samples from a specified channel.
* **`getTag(id)`**: Retrieves a tag by its ID.
* **`listCuePoints()`**: Lists all available cue points.
* **`listTags()`**: Lists all available tags.
* **`set_PMX(data)`**: Sets the PMX chunk data.
* **`setCuePoint(options)`**: Sets a cue point with specified options.
* **`setiXML(data)`**: Sets the iXML chunk data.
* **`setSample(channel, sampleIndex, value)`**: Sets a specific sample in a given channel to a new value.
* **`setTag(id, data)`**: Sets or updates a tag with the given ID and data.
* **`toALaw()`**: Encodes the audio data to ALaw format.
* **`toBase64()`**: Encodes the audio data to a Base64 string.
* **`toBitDepth(depth)`**: Converts the audio data to the specified bit depth.
* **`toBuffer()`**: Converts the audio data to an ArrayBuffer or Buffer.
* **`toDataURI()`**: Converts the audio data to a Data URI.
* **`toIMAADPCM()`**: Encodes the audio data to IMA ADPCM format.
* **`toMuLaw()`**: Encodes the audio data to MuLaw format.
* **`toRIFF()`**: Converts the audio data to RIFF format.
* **`toRIFX()`**: Converts the audio data to RIFX format.
* **`toSampleRate(rate)`**: Converts the audio data to the specified sample rate.
* **`updateLabel(id, label)`**: Updates the label of an existing cue point or tag.
```
--------------------------------
### Add cue points to files
Source: https://github.com/rochars/wavefile/blob/master/README.md
Manages cue points within a WAV file, allowing creation, deletion, and listing of these markers.
```APIDOC
## Cue Point Management
### Description
Enables the creation, deletion, and retrieval of cue points within a WAV file.
### Methods
- **`setCuePoint(cuePointObject)`**: Creates a new cue point.
- **`deleteCuePoint(index)`**: Deletes a cue point by its index.
- **`listCuePoints()`**: Retrieves all cue points in the file.
### Parameters
- **cuePointObject** (object) - Required for `setCuePoint` - An object containing cue point data. Must include `position` (number, in milliseconds). Optional fields include `label` (string).
- **index** (number) - Required for `deleteCuePoint` - The 1-based index of the cue point to delete.
### Request Example
```javascript
// Create a cue point with position
wav.setCuePoint({position: 1500});
// Create a cue point with position and label
wav.setCuePoint({position: 1500, label: 'some label'});
// Delete the first cue point
wav.deleteCuePoint(1);
// List all cue points
let cuePoints = wav.listCuePoints();
```
### Response
- `setCuePoint` and `deleteCuePoint` modify the `WaveFile` instance in place.
- `listCuePoints()` returns an array of cue point objects. Each object may contain properties like `position`, `label`, `end`, `dwName`, `dwPosition`, `fccChunk`, `dwChunkStart`, `dwBlockStart`, `dwSampleOffset`, `dwSampleLength`, `dwPurposeID`, `dwCountry`, `dwLanguage`, `dwDialect`, and `dwCodePage`.
```