Stream and file based music metadata parser for node.js. Supports any common audio and tagging format. TypeScript definitions are included.
Audio format | Description | Wiki | |
---|---|---|---|
AIFF / AIFF-C | Audio Interchange File Format | π | |
AAC | ADTS / Advanced Audio Coding | π | |
APE | Monkey's Audio | π | |
ASF | Advanced Systems Format | π | |
BWF | Broadcast Wave Format | π | |
DSDIFF | Philips DSDIFF | π | |
DSF | Sony's DSD Stream File | π | |
FLAC | Free Lossless Audio Codec | π | |
MP2 | MPEG-1 Audio Layer II | π | |
Matroska | Matroska (EBML), mka, mkv | π | |
MP3 | MPEG-1 / MPEG-2 Audio Layer III | π | |
MPC | Musepack SV7 | π | |
MPEG 4 | mp4, m4a, m4v | π | |
Ogg | Open container format | π | |
Opus | π | ||
Speex | π | ||
Theora | π | ||
Vorbis | Vorbis audio compression | π | |
WAV | RIFF WAVE | π | |
WebM | webm | π | |
WV | WavPack | π | |
WMA | Windows Media Audio | π |
Following tag header formats are supported:
- APE
- ASF
- EXIF 2.3
- ID3: ID3v1, ID3v1.1, ID3v2.2, ID3v2.3 & ID3v2.4
- iTunes
- RIFF/INFO
- Vorbis comment
- AIFF
It allows many tags to be accessed in audio format, and tag format independent way.
Support for MusicBrainz tags as written by Picard. ReplayGain tags are supported.
Support for encoding / format details:
- Bit rate
- Audio bit depth
- Duration
- Encoding profile (e.g. CBR, V0, V2)
Module: version 8 migrated from CommonJS to pure ECMAScript Module (ESM). JavaScript is compliant with ECMAScript 2019 (ES10). Requires Node.js β₯ 14.13.1 engine.
Although music-metadata is designed to run the node.js. music-metadata-browser can be used on the browser side.
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 |
β |
Dependency diagram:
graph TD;
MM(music-metadata)-->S(strtok3)
MM-->TY(token-types)
MM-->FT(file-type)
S(strtok3)-->P(peek-readable)
S-->TO("@tokenizer/token")
TY-->TO
TY-->IE("ieee754")
FT-->RWNS(readable-web-to-node-stream)
FT-->S
FT-->TY
TY-->NB(node:buffer)
RWNS-->RS(readable-stream)
RS-->SD(string_decoder)
SD-->SB(safe-buffer)
RS-->UD(util-deprecate)
RS-->I(inherits)
style NB fill:#F88,stroke:#A44
style SB fill:#F88,stroke:#A44
style SD fill:#CCC,stroke:#888
style IE fill:#CCC,stroke:#888
style UD fill:#CCC,stroke:#888
style I fill:#CCC,stroke:#888
Dependency list:
- tokenizer-token
- strtok3
- token-types
- file-type
- @tokenizer-token
- peek-readable
- readable-web-to-node-stream
Install using npm:
npm install music-metadata
or using yarn:
yarn add music-metadata
Import music-metadata:
import { parseFile } from 'music-metadata';
Import the methods you need, like parseFile
in this example.
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 data.
Parses the specified file (filePath
) and returns a promise with the metadata result (IAudioMetadata
).
parseFile(filePath: string, opts: IOptions = {}): Promise<IAudioMetadata>`
Example:
import { parseFile } from 'music-metadata';
import { inspect } from 'util';
(async () => {
try {
const metadata = await parseFile('../music-metadata/test/samples/MusicBrainz - Beth Hart - Sinner\'s Prayer [id3v2.3].V2.mp3');
console.log(inspect(metadata, { showHidden: false, depth: null }));
} catch (error) {
console.error(error.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 (via fileInfo.path
) is not provided, or not understood, music-metadata will try to derive the type from the content.
parseStream(stream: Stream.Readable, fileInfo?: IFileInfo | string, opts?: IOptions = {}): Promise<IAudioMetadata>`
Example:
import { parseStream } from 'music-metadata';
(async () => {
try {
const metadata = await parseStream(someReadStream, {mimeType: 'audio/mpeg', size: 26838});
console.log(metadata);
} catch (error) {
console.error(error.message);
}
})();
Parse metadata from an audio file, where the audio file is held in a Buffer.
parseBuffer(buffer: Buffer, fileInfo?: IFileInfo | string, opts?: IOptions = {}): Promise<IAudioMetadata>
Example:
import { parseBuffer } from 'music-metadata';
(async () => {
try {
const metadata = await parseBuffer(someBuffer, 'audio/mpeg');
console.log(metadata);
} catch (error) {
console.error(error.message);
}
})();
This is a low level function, reading from a strtok3 ITokenizer interface. music-metadata-browser is depended on this function.
This also enables special read modules like:
- streaming-http-token-reader for chunked HTTP(S) reading, using HTTP range requests.
Utility to Converts the native tags to a dictionary index on the tag identifier
orderTags(nativeTags: ITag[]): [tagId: string]: any[]
import { parseFile, orderTags } from 'music-metadata';
import { inspect } from 'util';
(async () => {
try {
const metadata = await parseFile('../test/samples/MusicBrainz - Beth Hart - Sinner\'s Prayer [id3v2.3].V2.mp3');
const orderedTags = orderTags(metadata.native['ID3v2.3']);
console.log(inspect(orderedTags, { showHidden: false, depth: null }));
} catch (error) {
console.error(error.message);
}
})();
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
Select cover image based on image type field, otherwise the first picture in file.
export function selectCover(pictures?: IPicture[]): IPicture | null
import { parseFile, selectCover } from 'music-metadata';
(async () => {
const {common} = await parseFile(filePath);
const cover = selectCover(common.picture); // pick the cover image
}
)();
duration
: default:false
, if set totrue
, it will parse the whole media file if required to determine the duration.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.includeChapters
default:false
, if set totrue
, it will parse chapters (currently only MP4 files). experimental functionality
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:
metadata.format
Audio format informationmetadata.common
Is a generic (abstract) way of reading metadata information.metadata.trackInfo
Is a generic (abstract) way of reading metadata information.metadata.native
List of native (original) tags found in the parsed audio file.
The questionmark ?
indicates the property is optional.
Audio format information. Defined in the TypeScript IFormat
interface:
format.container?: string
Audio encoding format. e.g.: 'flac'format.codec?
Name of the codec (algorithm used for the audio compression)format.codecProfile?: string
Codec profile / settingsformat.tagTypes?: TagType[]
List of tagging formats found in parsed audio fileformat.duration?: number
Duration in secondsformat.bitrate?: number
Number bits per second of encoded audio fileformat.sampleRate?: number
Sampling rate in Samples per second (S/s)format.bitsPerSample?: number
Audio bit depthformat.lossless?: boolean
True if lossless, false for lossy encodingformat.numberOfChannels?: number
Number of audio channelsformat.creationTime?: Date
Track creation timeformat.modificationTime?: Date
Track modification / tag update timeformat.trackGain?: number
Track gain in dBformat.albumGain?: number
Album gain in dB
To support advanced containers like Matroska or MPEG-4, which may contain multiple audio and video tracks, the experimental metadata.trackInfo
has been added,
metadata.trackInfo
is either undefined
or has an array of trackInfo
Audio format information. Defined in the TypeScript IFormat
interface:
trackInfo.type?: TrackType
Track typetrackInfo.codecName?: string
Codec nametrackInfo.codecSettings?: string
Codec settingstrackInfo.flagEnabled?: boolean
Set if the track is usable, default:true
trackInfo.flagDefault?: boolean
Set if that track (audio, video or subs) SHOULD be active if no language found matches the user preference.trackInfo.flagLacing?: boolean
Set if the track may contain blocks using lacingtrackInfo.name?: string
A human-readable track name.trackInfo.language?: string
Specifies the language of the tracktrackInfo.audio?: IAudioTrack
, seetrackInfo.audioTrack
trackInfo.video?: IVideoTrack
, seetrackInfo.videoTrack
audioTrack.samplingFrequency?: number
audioTrack.outputSamplingFrequency?: number
audioTrack.channels?: number
audioTrack.channelPositions?: Buffer
audioTrack.bitDepth?: number
videoTrack.flagInterlaced?: boolean
videoTrack.stereoMode?: number
videoTrack.pixelWidth?: number
videoTrack.pixelHeight?: number
videoTrack.displayWidth?: number
videoTrack.displayHeight?: number
videoTrack.displayUnit?: number
videoTrack.aspectRatioType?: number
videoTrack.colourSpace?: Buffer
videoTrack.gammaValue?: number
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.
import { parseStream } from 'music-metadata';
import { inspect } from 'util';
(async () => {
const metadata = await parseStream(someReadStream, {mimeType: 'audio/mpeg', size: 26838}, {duration: true});
console.log(inspect(metadata, {showHidden: false, depth: null}));
someReadStream.close();
}
)();
Via metadata.common.picture
you can access an array of cover art if present.
Each picture has this interface:
/**
* Attached picture, typically used for cover art
*/
export interface IPicture {
/**
* Image mime type
*/
format: string;
/**
* Image data
*/
data: Buffer;
/**
* Optional description
*/
description?: string;
/**
* Picture type
*/
type?: string;
}
To assign img
HTML-object you can do something like:
img.src = `data:${picture.format};base64,${picture.data.toString('base64')}`;
-
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
import { parseFile } from 'music-metadata'; function parseFiles(audioFiles) { const audioFile = audioFiles.shift(); if (audioFile) { return parseFile(audioFile).then(metadata => { // Do great things with the metadata return parseFiles(audioFiles); // process rest of the files AFTER we are finished }) } }
-
Use async/await
Use async/await
import { parseFile } from '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 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 (MIT)
Copyright Β© 2022 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.