• Stars
    star
    892
  • Rank 51,172 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 8 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Stream and file based music metadata parser for node. Supporting a wide range of audio and tag formats.

Node.js CI Build status NPM version npm downloads Coverage Status Codacy Badge CodeQL DeepScan grade Known Vulnerabilities Discord

music-metadata

Stream and file based music metadata parser for node.js. Supports any common audio and tagging format. TypeScript definitions are included.

Features

Support for audio file types

Audio format Description Wiki
AIFF / AIFF-C Audio Interchange File Format ๐Ÿ”— Apple rainbow logo
AAC ADTS / Advanced Audio Coding ๐Ÿ”— AAC logo
APE Monkey's Audio ๐Ÿ”— Monkey's Audio logo
ASF Advanced Systems Format ๐Ÿ”—
BWF Broadcast Wave Format ๐Ÿ”—
DSDIFF Philips DSDIFF ๐Ÿ”— DSD logo
DSF Sony's DSD Stream File ๐Ÿ”— DSD logo
FLAC Free Lossless Audio Codec ๐Ÿ”— FLAC logo
MP2 MPEG-1 Audio Layer II ๐Ÿ”—
Matroska Matroska (EBML), mka, mkv ๐Ÿ”— Matroska logo
MP3 MPEG-1 / MPEG-2 Audio Layer III ๐Ÿ”— MP3 logo
MPC Musepack SV7 ๐Ÿ”— musepack logo
MPEG 4 mp4, m4a, m4v ๐Ÿ”— mpeg 4 logo
Ogg Open container format ๐Ÿ”— Ogg logo
Opus ๐Ÿ”— Opus logo
Speex ๐Ÿ”— Speex logo
Theora ๐Ÿ”— Theora logo
Vorbis Vorbis audio compression ๐Ÿ”— Vorbis logo
WAV RIFF WAVE ๐Ÿ”—
WebM webm ๐Ÿ”— Matroska logo
WV WavPack ๐Ÿ”— WavPack logo
WMA Windows Media Audio ๐Ÿ”— Windows Media logo

Supported tag headers

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.

Audio format & encoding details

Support for encoding / format details:

Online demo's

Compatibility

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.

Browser Support

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 โœ“

Sponsor

Become a sponsor to Borewit

Usage

Installation

Install using npm:

npm install music-metadata

or using yarn:

yarn add music-metadata

Import music-metadata

Import music-metadata:

import { parseFile } from 'music-metadata';

Import the methods you need, like parseFile in this example.

Module Functions

There are two ways to parse (read) audio tracks:

  1. Audio (music) files can be parsed using direct file access using the parseFile function
  2. 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.

parseFile function

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);
  }
})();

parseStream function

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);
  }
})();

parseBuffer function

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);
  }
})();

parseFromTokenizer function

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:

orderTags function

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);
  }
})();

ratingToStars function

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

selectCover function

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
}
)();

Options

  • 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.
  • includeChapters default: false, if set to true, 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.

Metadata result

If the returned promise resolves, the metadata (TypeScript IAudioMetadata interface) contains:

  • metadata.format Audio format information
  • metadata.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 / settings
  • format.tagTypes?: TagType[] List of tagging formats found in parsed audio file
  • format.duration?: number Duration in seconds
  • format.bitrate?: number Number bits per second of encoded audio file
  • format.sampleRate?: number Sampling rate in Samples per second (S/s)
  • format.bitsPerSample?: number Audio bit depth
  • format.lossless?: boolean True if lossless, false for lossy encoding
  • format.numberOfChannels?: number Number of audio channels
  • format.creationTime?: Date Track creation time
  • format.modificationTime?: Date Track modification / tag update time
  • format.trackGain?: number Track gain in dB
  • format.albumGain?: number Album gain in dB

metadata.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

trackInfo

Audio format information. Defined in the TypeScript IFormat interface:

  • trackInfo.type?: TrackType Track type
  • trackInfo.codecName?: string Codec name
  • trackInfo.codecSettings?: string Codec settings
  • trackInfo.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 lacing
  • trackInfo.name?: string A human-readable track name.
  • trackInfo.language?: string Specifies the language of the track
  • trackInfo.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.

Examples

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();
  }
)();

Access cover art

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')}`;

Frequently Asked Questions

  1. 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:

    1. 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
          })
        }
      }
    2. 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
          }
      }
    3. Use a specialized module to traverse files

      There are specialized modules to traversing (walking) files and directory, like walk.

Licence

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.

More Repositories

1

music-metadata-browser

Browser version of music-metadata parser Supporting a wide range of audio and tag formats.
TypeScript
239
star
2

musicbrainz-api

Node MusicBrainz API client for reading and submitting metadata
TypeScript
148
star
3

readable-web-to-node-stream

Converts a Web-API readable-stream into a Node readable-stream.
TypeScript
44
star
4

strtok3

Promise based streaming tokenizer
TypeScript
33
star
5

audio-tag-analyzer

Extracts metadata music metadata found in audio files
TypeScript
31
star
6

listFix

listFix() - Playlist Repair Done Right
Java
13
star
7

token-types

A primitive token library used to read from, and to write a node Buffer
TypeScript
11
star
8

music-metadata-react

React application to test integration with music-metadata-browser
JavaScript
11
star
9

tokenizer-s3

Amazon S3 tokenizer
TypeScript
8
star
10

tokenizer-http

Fetch HTTP streamed chunks using RFC-7233 range requests
TypeScript
8
star
11

peek-readable

A promise based asynchronous stream reader, which makes reading from a stream easy.
TypeScript
7
star
12

music-metadata-s3

Extension for music-metadata to retrieve metadata from files stored on AWS S3 cloud storage
JavaScript
5
star
13

tokenizer-range

Range-request tokenizer adapter
TypeScript
3
star
14

lizzy

Multimedia playlist parser, supporting a wide range of playlist file formats.
Java
3
star
15

tokenizer-token

TypeScript definition for strtok3 token
2
star
16

gazelle-client

Gazelle API client
TypeScript
2
star
17

musicbrainz-augmentation

MusicBrainz metadata augmentation using Spotify metadata
TypeScript
1
star
18

t-readable

Split a readable-stream into 2 or more readable-streams
TypeScript
1
star
19

ogg-radio-stream

Test to listen to an infinite Ogg stream
JavaScript
1
star
20

file-type-example

file-type examples
TypeScript
1
star