Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
music-metadata
Advanced tools
Music metadata parser for Node.js, supporting virtual any audio and tag format.
The music-metadata npm package is a powerful tool for parsing and extracting metadata from audio files. It supports a wide range of audio formats and provides detailed information about the audio file, including tags, format, and technical properties.
Extract Basic Metadata
This feature allows you to extract basic metadata from an audio file, such as title, artist, album, and genre. The code sample demonstrates how to use the `parseFile` method to read and log metadata from an MP3 file.
const mm = require('music-metadata');
const fs = require('fs');
async function getMetadata(filePath) {
try {
const metadata = await mm.parseFile(filePath);
console.log(metadata);
} catch (error) {
console.error(error.message);
}
}
getMetadata('path/to/audio/file.mp3');
Extract Format Information
This feature allows you to extract format information from an audio file, such as the container type, codec, sample rate, and bit rate. The code sample demonstrates how to use the `parseFile` method to read and log format information from an MP3 file.
const mm = require('music-metadata');
const fs = require('fs');
async function getFormatInfo(filePath) {
try {
const metadata = await mm.parseFile(filePath);
console.log(metadata.format);
} catch (error) {
console.error(error.message);
}
}
getFormatInfo('path/to/audio/file.mp3');
Extract Technical Properties
This feature allows you to extract technical properties from an audio file, such as duration, number of channels, and bit depth. The code sample demonstrates how to use the `parseFile` method to read and log technical properties from an MP3 file.
const mm = require('music-metadata');
const fs = require('fs');
async function getTechnicalProperties(filePath) {
try {
const metadata = await mm.parseFile(filePath);
console.log(metadata.common);
} catch (error) {
console.error(error.message);
}
}
getTechnicalProperties('path/to/audio/file.mp3');
The node-id3 package is focused on reading and writing ID3 tags in MP3 files. It provides a simpler interface for handling ID3 tags compared to music-metadata, but it is limited to MP3 files and does not support other audio formats.
The musicmetadata package is another tool for extracting metadata from audio files. It supports a variety of audio formats and provides similar functionality to music-metadata. However, it is less actively maintained and may not support the latest audio formats and tags.
The id3js package is a JavaScript library for reading ID3 tags from MP3 files. It is designed to work in both Node.js and browser environments. While it offers similar functionality to music-metadata for MP3 files, it does not support other audio formats.
Key features:
The music-metadata
module is ideal for developers working on media applications, music players, or any project that requires access to detailed audio file metadata.
Module: version 8 migrated from CommonJS to pure ECMAScript Module (ESM). The distributed JavaScript codebase is compliant with the ECMAScript 2020 (11th Edition) standard.
This module requires a Node.js ≥ 16 engine. It can also be used in a browser environment when bundled with a module bundler.
If you appreciate my work and want to support the development of open-source projects like music-metadata, file-type, and listFix(), consider becoming a sponsor or making a small contribution. Your support helps sustain ongoing development and improvements. Become a sponsor to Borewit
or
Audio format | Description | Wiki | |
---|---|---|---|
AIFF / AIFF-C | Audio Interchange File Format | :link: | |
AAC | ADTS / Advanced Audio Coding | :link: | |
APE | Monkey's Audio | :link: | |
ASF | Advanced Systems Format | :link: | |
BWF | Broadcast Wave Format | :link: | |
DSDIFF | Philips DSDIFF | :link: | |
DSF | Sony's DSD Stream File | :link: | |
FLAC | Free Lossless Audio Codec | :link: | |
MP2 | MPEG-1 Audio Layer II | :link: | |
Matroska | Matroska (EBML), mka, mkv | :link: | |
MP3 | MPEG-1 / MPEG-2 Audio Layer III | :link: | |
MPC | Musepack SV7 | :link: | |
MPEG 4 | mp4, m4a, m4v | :link: | |
Ogg | Open container format | :link: | |
Opus | :link: | ||
Speex | :link: | ||
Theora | :link: | ||
Vorbis | Vorbis audio compression | :link: | |
WAV | RIFF WAVE | :link: | |
WebM | webm | :link: | |
WV | WavPack | :link: | |
WMA | Windows Media Audio | :link: |
Following tag header formats are supported:
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:
Dependency diagram:
graph TD;
MMN("music-metadata (Node.js entry point)")-->MMP
MMN-->FTN
MMP("music-metadata (primary entry point)")-->S(strtok3)
MMP-->TY(token-types)
MMP-->FTP
MMP-->UAE
FTN("file-type (Node.js entry point)")-->FTP
FTP("file-type (primary entry point)")-->S
S(strtok3)-->P(peek-readable)
S(strtok3)-->TO("@tokenizer/token")
TY(token-types)-->TO
TY-->IE("ieee754")
FTP-->TY
NS("node:stream")
FTN-->NS
FTP-->UAE(uint8array-extras)
style NS fill:#F88,stroke:#A44
style IE fill:#CCC,stroke:#888
style FTN fill:#FAA,stroke:#A44
style MMN fill:#FAA,stroke:#A44
Dependency list:
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 multiple ways to parse (read) audio tracks:
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.
This method can only be used if the JavaScript engine is Node.js. To read from a File, please see fileTypeFromBlob(blob).
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);
}
})();
Only available using a Node.js JavaScript engines.
Parses the provided audio stream for metadata.
The stream should be of type Node.js Readable.
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);
}
})();
Parses the provided audio web stream for metadata.
The stream should be of type ReadableStream.
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.
parseWebStream(stream: ReadableStream<Uint8Array>, fileInfo?: IFileInfo | string, opts?: IOptions = {}): Promise<IAudioMetadata>`
This method can only be used if with a Node.js JavaScript engine.
Parse an audio file from a Blob or File.
const musicMetadata = require('music-metadata');
let blob;
musicMetadata.parseBlob(blob).then(metadata => {
// metadata has all the metadata found in the blob or file
});
Or with async/await if you prefer:
(async () => {
let blob; // File or Blob
const metadata = await musicMetadata.parseBlob(blob);
// metadata has all the metadata found in the blob or file
});
Parse metadata from an audio file, where the audio file is held in a Buffer.
parseBuffer(buffer: Uint8Array, 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.
This also enables special read modules like:
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 to true
, it will parse the whole media file if required to determine the duration.observer: (update: MetadataEvent) => void;
: Will be called after each change to common
(generic) tag, or format
properties.skipCovers
: default: false
, if set to true
, it will not return embedded cover-art (images).skipPostHeaders? boolean
default: false
, if set to true
, it will not search all the entire track for additional headers. Only recommenced to use in combination with streams.mkvUseIndex
default: false
, if set to true
, in Matroska based files, use the SeekHead element index to skip segment/cluster elements..
experimental functionality
Can have a significant performance impact if enabled.
Possible side effect can be that certain metadata maybe skipped, depending on the index.
If there is no SeekHead element present in the Matroska file, this flag has no effect.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.metadata.format
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 dBmetadata.trackInfo
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
, see trackInfo.audioTrack
trackInfo.video?: IVideoTrack
, see trackInfo.videoTrack
trackInfo.audioTrack
audioTrack.samplingFrequency?: number
audioTrack.outputSamplingFrequency?: number
audioTrack.channels?: number
audioTrack.channelPositions?: Buffer
audioTrack.bitDepth?: number
trackInfo.videoTrack
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
metadata.common
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:
import {uint8ArrayToBase64} from 'uint8array-extras';
img.src = `data:${picture.format};base64,${uint8ArrayToBase64(picture.data)}`;
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.
FAQs
Music metadata parser for Node.js, supporting virtual any audio and tag format.
The npm package music-metadata receives a total of 241,336 weekly downloads. As such, music-metadata popularity was classified as popular.
We found that music-metadata demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
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.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.