Stream and file based music metadata parser for node.
Audio format | Description | Wiki | |
---|---|---|---|
AIFF / AIFF-C | Audio Interchange File Format | 🔗 | |
AAC | ADTS / Advanced Audio Coding | 🔗 | |
APE | Monkey's Audio | 🔗 | |
ASF | Advanced Systems Format | 🔗 | |
DSDIFF | Philips DSDIFF | 🔗 | |
DSF | Sony's DSD Stream File | 🔗 | |
FLAC | Free Lossless Audio Codec | 🔗 | |
MP2 | MPEG-1 Audio Layer II | 🔗 | |
MP3 | MPEG-1 / MPEG-2 Audio Layer III | 🔗 | |
MPC | Musepack SV7 | 🔗 | |
MPEG 4 | mp4, m4a, m4v | 🔗 | |
Ogg / Opus | 🔗 | ||
Ogg / Speex | 🔗 | ||
Ogg / Vorbis | 🔗 | ||
WAV | 🔗 | ||
WV | WavPack | 🔗 | |
WMA | Windows Media Audio | 🔗 |
Following tag header formats are supported:
Support for MusicBrainz tags as written by Picard.
Support for encoding / format details:
- Bit rate
- Audio bit depth
- Duration
- Encoding profile (e.g. CBR, V0, V2)
The JavaScript in runtime is compliant with ECMAScript 2017 (ES8). Requires Node.js® version 6 or higher.
Although music-metadata is designed to run in Node.js, it can also be used to run in the browser:
- music-metadata-browser is better suitable to run in the browser.
To avoid Node fs
dependency inclusion, you may use a sub-module inclusion:
import * as mm from 'music-metadata/lib/core';
function | music-metadata |
music-metadata/lib/core |
---|---|---|
parseBuffer |
✓ | ✓ |
parseStream * |
✓ | ✓ |
parseFromTokenizer |
✓ | ✓ |
parseFile |
✓ |
Not required, but would be extremely motivating. PayPal.me
Install via npm:
npm install music-metadata
or yarn
yarn add music-metadata
Import music-metadata in JavaScript:
const mm = require('music-metadata');
This is how it's done in TypeScript:
import * as mm from 'music-metadata';
There are two ways to parse (read) audio tracks:
- Audio (music) files can be parsed using direct file access using the parseFile function
- Using Node.js streams using the parseStream function.
Direct file access tends to be a little faster, because it can 'jump' to various parts in the file without being obliged to read intermediate date.
Parses the specified file (filePath
) and returns a promise with the metadata result (IAudioMetadata
).
parseFile(filePath: string, opts: IOptions = {}): Promise<IAudioMetadata>`
Javascript example:
const mm = require('music-metadata');
const util = require('util')
mm.parseFile('../test/samples/MusicBrainz-multiartist [id3v2.4].V2.mp3', {native: true})
.then( metadata => {
console.log(util.inspect(metadata, { showHidden: false, depth: null }));
})
.catch( err => {
console.error(err.message);
});
Typescript example:
import * as mm from 'music-metadata';
import * as util from 'util';
mm.parseFile('../test/samples/MusicBrainz-multiartist [id3v2.4].V2.mp3')
.then( metadata => {
console.log(util.inspect(metadata, {showHidden: false, depth: null}));
})
.catch((err) => {
console.error(err.message);
});
Parses the provided audio stream for metadata.
It is recommended to provide the corresponding MIME-type.
An extension (e.g.: .mp3
), filename or path will also work.
If the MIME-type or filename is not provided, or not understood, music-metadata will try to derive the type from the content.
parseStream(stream: Stream.Readable, mimeType?: string, opts?: IOptions = {}): Promise<IAudioMetadata>`
Example:
mm.parseStream(someReadStream, 'audio/mpeg', { fileSize: 26838 })
.then( metadata => {
console.log(util.inspect(metadata, { showHidden: false, depth: null }));
someReadStream.destroy();
});
Parses content of the provided buffer for metadata.
parseBuffer(buffer: Buffer, mimeType?: string, opts?: IOptions = {}): Promise<IAudioMetadata>
Example:
mm.parseBuffer(someBuffer, 'audio/mpeg', { fileSize: 26838 })
.then( metadata => {
console.log(util.inspect(metadata, { showHidden: false, depth: null }));
});
Utility to Converts the native tags to a dictionary index on the tag identifier
orderTags(nativeTags: ITag[]): [tagId: string]: any[]
Can be used to convert the normalized rating value to the 0..5 stars, where 0 an undefined rating, 1 the star the lowest rating and 5 the highest rating.
ratingToStars(rating: number): number
duration
: default:false
, if set totrue
, it will parse the whole media file if required to determine the duration.fileSize
: only provide this in combination withparseStream
function.native
: default:false
, if set totrue
, it will return native tags in addition to thecommon
tags.observer: (update: MetadataEvent) => void;
: Will be called after each change tocommon
(generic) tag, orformat
properties.skipCovers
: default:false
, if set totrue
, it will not return embedded cover-art (images).skipPostHeaders? boolean
default:false
, if set totrue
, it will not search all the entire track for additional headers. Only recommenced to use in combination with streams.
Although in most cases duration is included, in some cases it requires music-metadata
parsing the entire file.
To enforce parsing the entire file if needed you should set duration
to true
.
If the returned promise resolves, the metadata (TypeScript IAudioMetadata
interface) contains:
format: IFormat
Audio format informationnative: INativeTags
List of native (original) tags found in the parsed audio file. If the native option is set to false, this property is not defined.common: ICommonTagsResult
Is a generic (abstract) way of reading metadata information.
Audio format information. Defined in the TypeScript IFormat
interface:
container?: string
Audio encoding format. e.g.: 'flac'codec?
Name of the codec (algorithm used for the audio compression)codecProfile?: string
Codec profile / settingstagTypes?: TagType[]
List of tagging formats found in parsed audio fileduration?: number
Duration in secondsbitrate?: number
Number bits per second of encoded audio filesampleRate?: number
Sampling rate in Samples per second (S/s)bitsPerSample?: number
Audio bit depthlossless?: boolean
True if lossless, false for lossy encodingnumberOfChannels?: number
Number of audio channelsnumberOfSamples?: number
Number of samples frames, one sample contains all channels. The duration is: numberOfSamples / sampleRate
Common tag documentation is automatically generated.
In order to read the duration of a stream (with the exception of file streams), in some cases you should pass the size of the file in bytes.
mm.parseStream(someReadStream, 'audio/mpeg', { duration: true, fileSize: 26838 })
.then( function (metadata) {
console.log(util.inspect(metadata, { showHidden: false, depth: null }));
someReadStream.close();
});
-
How can I traverse (a long) list of files?
What is important that file parsing should be done in a sequential manner. In a plain loop, due to the asynchronous character (like most JavaScript functions), it would cause all the files to run in parallel which is will cause your application to hang in no time. There are multiple ways of achieving this:
-
Using recursion
const mm = require('music-metadata') function parseFiles(audioFiles) { const audioFile = audioFiles.shift(); if (audioFile) { return mm.parseFile(audioFile).then(metadata => { // Do great things with the metadata return parseFiles(audioFiles); // process rest of the files AFTER we are finished }) } return Promise.resolve(); }
-
Use async/await
Use async/await
const mm = require('music-metadata') // it is required to declare the function 'async' to allow the use of await async function parseFiles(audioFiles) { for (const audioFile of audioFiles) { // await will ensure the metadata parsing is completed before we move on to the next file const metadata = await mm.parseFile(audioFile); // Do great things with the metadata } }
-
Use a specialized module to traverse files
There are specialized modules to traversing (walking) files and directory, like walk.
-
(The MIT License)
Copyright (c) 2017 Borewit
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.