music-metadata 10.8.0-beta.2 → 10.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,846 +1,846 @@
1
- [![Node.js CI](https://github.com/Borewit/music-metadata/actions/workflows/nodejs-ci.yml/badge.svg?branch=master)](https://github.com/Borewit/music-metadata/actions?query=branch%3Amaster)
2
- [![NPM version](https://img.shields.io/npm/v/music-metadata.svg)](https://npmjs.org/package/music-metadata)
3
- [![npm downloads](http://img.shields.io/npm/dm/music-metadata.svg)](https://npmcharts.com/compare/music-metadata,jsmediatags,musicmetadata,node-id3,mp3-parser,id3-parser,wav-file-info?start=600&interval=30)
4
- [![Coverage Status](https://coveralls.io/repos/github/Borewit/music-metadata/badge.svg?branch=master)](https://coveralls.io/github/Borewit/music-metadata?branch=master)
5
- [![Codacy Badge](https://api.codacy.com/project/badge/Grade/57d731b05c9e41889a2a17cb4b0384d7)](https://app.codacy.com/app/Borewit/music-metadata?utm_source=github.com&utm_medium=referral&utm_content=Borewit/music-metadata&utm_campaign=Badge_Grade_Dashboard)
6
- [![CodeQL](https://github.com/Borewit/music-metadata/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/Borewit/music-metadata/actions/workflows/codeql-analysis.yml)
7
- [![DeepScan grade](https://deepscan.io/api/teams/5165/projects/6938/branches/61821/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=5165&pid=6938&bid=61821)
8
- [![Known Vulnerabilities](https://snyk.io/test/github/Borewit/music-metadata/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/music-metadata?targetFile=package.json)
9
- [![Discord](https://img.shields.io/discord/460524735235883049.svg)](https://discord.gg/KyBr6sb)
10
-
11
- # music-metadata
12
-
13
- Key features:
14
- - **Comprehensive Format Support**: Supports popular audio formats like MP3, MP4, FLAC, Ogg, WAV, AIFF, and more.
15
- - **Extensive Metadata Extraction**: Extracts detailed metadata, including ID3v1, ID3v2, APE, Vorbis, and iTunes/MP4 tags.
16
- - **Streaming Support**: Efficiently handles large audio files by reading metadata from streams, making it suitable for server-side and browser-based applications.
17
- - **Promise-Based API**: Provides a modern, promise-based API for easy integration into asynchronous workflows.
18
- - **Cross-Platform**: Works in both [Node.js](https://nodejs.org/) and browser environments with the help of bundlers like [Webpack](https://webpack.js.org/) or [Rollup](https://rollupjs.org/introduction/).
19
-
20
- The [`music-metadata`](https://github.com/Borewit/music-metadata) module is ideal for developers working on media applications, music players, or any project that requires access to detailed audio file metadata.
21
-
22
- ## Compatibility
23
-
24
- Module: version 8 migrated from [CommonJS](https://en.wikipedia.org/wiki/CommonJS) to [pure ECMAScript Module (ESM)](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).
25
- The distributed JavaScript codebase is compliant with the [ECMAScript 2020 (11th Edition)](https://en.wikipedia.org/wiki/ECMAScript_version_history#11th_Edition_%E2%80%93_ECMAScript_2020) standard.
26
-
27
- > [!NOTE]
28
- > See also [CommonJS backward Compatibility](#commonjs-backward-compatibility)
29
-
30
- This module requires a [Node.js ≥ 16](https://nodejs.org/en/about/previous-releases) engine.
31
- It can also be used in a browser environment when bundled with a module bundler.
32
-
33
- ## Support the Project
34
- If you find this project useful and would like to support its development, consider sponsoring or contributing:
35
-
36
- - [Become a sponsor to Borewit](https://github.com/sponsors/Borewit)
37
-
38
- - Buy me a coffee:
39
-
40
- <a href="https://www.buymeacoffee.com/borewit" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy me A coffee" height="41" width="174"></a>
41
-
42
- ## Features
43
-
44
- ### Support for audio file types
45
-
46
- | Audio format | Description | Wiki | |
47
- | ------------- |---------------------------------| -------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------:|
48
- | AIFF / AIFF-C | Audio Interchange File Format | [:link:](https://wikipedia.org/wiki/Audio_Interchange_File_Format) | <img src="https://upload.wikimedia.org/wikipedia/commons/8/84/Apple_Computer_Logo_rainbow.svg" width="40" alt="Apple rainbow logo"> |
49
- | AAC | ADTS / Advanced Audio Coding | [:link:](https://en.wikipedia.org/wiki/Advanced_Audio_Coding) | <img src="https://svgshare.com/i/UT8.svg" width="40" alt="AAC logo"> |
50
- | APE | Monkey's Audio | [:link:](https://wikipedia.org/wiki/Monkey's_Audio) | <img src="https://foreverhits.files.wordpress.com/2015/05/ape_audio.jpg" width="40" alt="Monkey's Audio logo"> |
51
- | ASF | Advanced Systems Format | [:link:](https://wikipedia.org/wiki/Advanced_Systems_Format) | |
52
- | BWF | Broadcast Wave Format | [:link:](https://en.wikipedia.org/wiki/Broadcast_Wave_Format) | |
53
- | DSDIFF | Philips DSDIFF | [:link:](https://wikipedia.org/wiki/Direct_Stream_Digital) | <img src="https://upload.wikimedia.org/wikipedia/commons/b/bc/DSDlogo.svg" width="80" alt="DSD logo"> |
54
- | DSF | Sony's DSD Stream File | [:link:](https://wikipedia.org/wiki/Direct_Stream_Digital) | <img src="https://upload.wikimedia.org/wikipedia/commons/b/bc/DSDlogo.svg" width="80" alt="DSD logo"> |
55
- | FLAC | Free Lossless Audio Codec | [:link:](https://wikipedia.org/wiki/FLAC) | <img src="https://upload.wikimedia.org/wikipedia/commons/a/a2/FLAC_logo_vector.svg" width="80" alt="FLAC logo"> |
56
- | MP2 | MPEG-1 Audio Layer II | [:link:](https://wikipedia.org/wiki/MPEG-1_Audio_Layer_II) | |
57
- | Matroska | Matroska (EBML), mka, mkv | [:link:](https://wikipedia.org/wiki/Matroska) | <img src="https://upload.wikimedia.org/wikipedia/commons/1/1a/Matroska_2010.svg" width="80" alt="Matroska logo"> |
58
- | MP3 | MPEG-1 / MPEG-2 Audio Layer III | [:link:](https://wikipedia.org/wiki/MP3) | <img src="https://upload.wikimedia.org/wikipedia/commons/e/ea/Mp3.svg" width="80" alt="MP3 logo"> |
59
- | MPC | Musepack SV7 | [:link:](https://wikipedia.org/wiki/Musepack) | <img src="https://www.musepack.net/pictures/musepack_logo.png" width="80" alt="musepack logo"> |
60
- | MPEG 4 | mp4, m4a, m4v | [:link:](https://wikipedia.org/wiki/MPEG-4) | <img src="https://svgshare.com/i/UU3.svg" width="80" alt="mpeg 4 logo"> |
61
- | Ogg | Open container format | [:link:](https://en.wikipedia.org/wiki/Ogg) | <img src="https://upload.wikimedia.org/wikipedia/commons/a/a1/Ogg_Logo.svg" width="80" alt="Ogg logo"> |
62
- | Opus | | [:link:](https://wikipedia.org/wiki/Opus_(audio_format)) | <img src="https://upload.wikimedia.org/wikipedia/commons/0/02/Opus_logo2.svg" width="80" alt="Opus logo"> |
63
- | Speex | | [:link:](https://wikipedia.org/wiki/Speex) | <img src="https://upload.wikimedia.org/wikipedia/commons/b/b5/Speex_logo_2006.svg" width="80" alt="Speex logo"> |
64
- | Theora | | [:link:](https://en.wikipedia.org/wiki/Theora) | <img src="https://upload.wikimedia.org/wikipedia/commons/5/57/Theora_logo_2007.svg" width="70" alt="Theora logo"> |
65
- | Vorbis | Vorbis audio compression | [:link:](https://wikipedia.org/wiki/Ogg_Vorbis) | <img src="https://upload.wikimedia.org/wikipedia/commons/8/8d/Xiph.Org_logo_square.svg" width="70" alt="Vorbis logo"> |
66
- | WAV | RIFF WAVE | [:link:](https://wikipedia.org/wiki/WAV) | |
67
- | WebM | webm | [:link:](https://wikipedia.org/wiki/WebM) | <img src="https://upload.wikimedia.org/wikipedia/commons/3/34/WebM_logo.svg" width="80" alt="Matroska logo"> |
68
- | WV | WavPack | [:link:](https://wikipedia.org/wiki/WavPack) | <img src="http://www.wavpack.com/wavpacklogo.svg" width="60" alt="WavPack logo"> |
69
- | WMA | Windows Media Audio | [:link:](https://wikipedia.org/wiki/Windows_Media_Audio) | <img src="https://upload.wikimedia.org/wikipedia/commons/7/76/Windows_Media_Player_simplified_logo.svg" width="40" alt="Windows Media logo"> |
70
-
71
- ### Supported tag headers
72
-
73
- Following tag header formats are supported:
74
- - [APE](https://wikipedia.org/wiki/APE_tag)
75
- - [ASF](https://wikipedia.org/wiki/Advanced_Systems_Format)
76
- - EXIF 2.3
77
- - [ID3](https://wikipedia.org/wiki/ID3): ID3v1, ID3v1.1, ID3v2.2, [ID3v2.3](http://id3.org/id3v2.3.0) & [ID3v2.4](http://id3.org/id3v2.4.0-frames)
78
- - [iTunes](https://github.com/sergiomb2/libmp4v2/wiki/iTunesMetadata)
79
- - [RIFF](https://wikipedia.org/wiki/Resource_Interchange_File_Format)/INFO
80
- - [Vorbis comment](https://wikipedia.org/wiki/Vorbis_comment)
81
- - [AIFF](https://wikipedia.org/wiki/Audio_Interchange_File_Format)
82
-
83
- Following lyric formats are supported:
84
- - [LRC](https://en.wikipedia.org/wiki/LRC_(file_format))
85
- - Synchronized lyrics (SYLT)
86
- - Unsynchronized lyrics (USULT)
87
-
88
- Support for [MusicBrainz](https://musicbrainz.org/) tags as written by [Picard](https://picard.musicbrainz.org/).
89
- [ReplayGain](https://wiki.hydrogenaud.io/index.php?title=ReplayGain) tags are supported.
90
-
91
- ### Audio format & encoding details
92
-
93
- Support for encoding / format details:
94
- - [Bit rate](https://wikipedia.org/wiki/Bit_rate)
95
- - [Audio bit depth](https://wikipedia.org/wiki/Audio_bit_depth)
96
- - Duration
97
- - Encoding profile (e.g. [CBR](https://en.wikipedia.org/wiki/Constant_bitrate), V0, V2)
98
-
99
-
100
- ## Online demo's
101
- - [<img src="https://raw.githubusercontent.com/Borewit/audio-tag-analyzer/master/src/assets/icon/audio-tag-analyzer.svg" width="40">Audio Tag Analyzer](https://audio-tag-analyzer.netlify.app/)
102
- - [<img src="https://cdn.sanity.io/images/3do82whm/next/ba8c847f13a5fa39d88f8bc9b7846b7886531b18-2500x2500.svg" width="40"> Webamp](https://webamp.org/)
103
- - Expected to be released soon: [Overtone](https://overtone.pro/) by [Johannes Schickling](https://github.com/schickling)
104
-
105
- ## Usage
106
-
107
- ### Installation
108
- Install using [npm](http://npmjs.org/):
109
-
110
- ```bash
111
- npm install music-metadata
112
- ```
113
- or using [yarn](https://yarnpkg.com/):
114
- ```bash
115
- yarn add music-metadata
116
- ```
117
-
118
- ## API Documentation
119
-
120
- ### Overview
121
-
122
- **Node.js specific** functions to read an audio file or stream:
123
- 1. **File Parsing**: Parse audio files directly from the filesystem using the [parseFile function](#parsefile-function)
124
- 1. **Stream Parsing**: Parse audio metadata from a Node.js [Readable stream](https://nodejs.org/api/stream.html#class-streamreadable) using the [parseStream function](#parsewebstream-function).
125
-
126
- **Cross-platform** functions available to read an audio file or stream:
127
-
128
- There are multiple ways to parse (read) audio tracks:
129
- 1. **Web Stream Parsing**: Parse audio data from a web-compatible [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) using the [parseWebStream function](#parsewebstream-function).
130
- 1. **Blob Parsing**: Parse audio metadata from a (Web API) [Blob](https://developer.mozilla.org/docs/Web/API/Blob) or [File](https://developer.mozilla.org/docs/Web/API/File) using the [parseBlob function](#parseblob-function).
131
- 1. **Buffer Parsing**: Parse audio metadata from a [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) or [Buffer](https://nodejs.org/api/buffer.html) using the [parseBuffer function](#parsebuffer-function).
132
- 1. **Tokenizer Parsing:** Use a custom or third-party [strtok3](https://github.com/Borewit/strtok3) `ITokenizer` to parse using the [parseFromTokenizer function](#parsefromtokenizer-function).
133
-
134
- > [!NOTE]
135
- > Direct file access in Node.js is generally faster because it can 'jump' to various parts of the file without reading intermediate data.
136
-
137
- ### Node.js specific function
138
- These functions are tailored for Node.js environments and leverage Node.js-specific APIs,
139
- making them incompatible with browser-based JavaScript engines.
140
-
141
- #### `parseFile` function
142
-
143
- The `parseFile` function is intended for extracting metadata from audio files on the local filesystem in a Node.js environment.
144
- It reads the specified file, parses its audio metadata, and returns a promise that resolves with this information.
145
-
146
- ##### Syntax
147
- ```ts
148
- parseFile(filePath: string, options?: IOptions): Promise<IAudioMetadata>
149
- ```
150
-
151
- ##### Parameters
152
-
153
- - `filePath`: `string`
154
-
155
- The path to the media file from which metadata should be extracted.
156
- This should be a valid path to an audio file on the local filesystem.
157
-
158
- - `options`: [IOptions](#ioptions-interface) (optional)
159
-
160
- An optional configuration object that allows customization of the parsing process.
161
- These options can include whether to calculate the file's duration, skip embedded cover art,
162
- or other parsing behaviors.
163
-
164
- ##### Returns
165
-
166
- - `Promise<IAudioMetadata>`:
167
-
168
- A promise that resolves to an IAudioMetadata object containing metadata about the audio file.
169
- The metadata includes details such as the file format, codec, duration, bit rate, and any embedded tags like album, artist, or track information.
170
-
171
- ##### Usage Notes
172
-
173
- - This function is **Node.js-only** and relies on Node.js-specific APIs to access the filesystem.
174
-
175
- - For browser environments, consider using the [parseBlob](#parseblob-function) to parse [File object](https://developer.mozilla.org/en-US/docs/Web/API/File) objects.
176
-
177
- ##### Example:
178
-
179
- The following example demonstrates how to use the parseFile function to read metadata from an audio file:
180
- ```js
181
- import { parseFile } from 'music-metadata';
182
- import { inspect } from 'util';
183
-
184
- (async () => {
185
- try {
186
- const filePath = '../music-metadata/test/samples/MusicBrainz - Beth Hart - Sinner\'s Prayer [id3v2.3].V2.mp3';
187
- const metadata = await parseFile(filePath);
188
-
189
- // Output the parsed metadata to the console in a readable format
190
- console.log(inspect(metadata, { showHidden: false, depth: null }));
191
- } catch (error) {
192
- console.error('Error parsing metadata:', error.message);
193
- }
194
- })();
195
- ```
196
-
197
- #### `parseStream` function
198
-
199
- The parseStream function is used to parse metadata from an audio track provided as a Node.js [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) stream.
200
- This is particularly useful for processing audio data that is being streamed or piped from another source, such as a web server or file system.
201
-
202
- ##### Syntax:
203
- ```ts
204
- parseStream(stream: Readable, fileInfo?: IFileInfo | string, options?: IOptions): Promise<IAudioMetadata>
205
- ```
206
-
207
- ##### Parameters:
208
-
209
- - `stream`: `Readable`:
210
-
211
- The Node.js [Readable](https://nodejs.org/api/stream.html#class-streamreadable) stream from which the audio data is read.
212
- This stream should provide the raw audio data to be analyzed.
213
-
214
- - `fileInfo`: `IFileInfo` (optional)
215
-
216
- An object containing file-related information or a string representing the MIME-type of the audio stream.
217
- The fileInfo parameter can help the parser to correctly identify the audio format and may include:
218
-
219
- - `mimeType`: A string representing the [MIME-type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) (e.g., `audio/mpeg`).
220
-
221
- If provided, it is assumed the streamed file content is to be the MIME-type.
222
- If not provided, the parser will attempt to determine the format based on the content of the stream.
223
-
224
- - `size`: The total size of the audio stream in bytes (useful for streams with a known length).
225
-
226
- - `path`: A string representing the file path or filename, which can also assist in determining the format.
227
-
228
- - `options`: `IOptions` (optional)
229
-
230
- An optional object containing additional parsing options.
231
- These options allow you to customize the parsing process,
232
- such as whether to calculate the duration or skip cover art extraction.
233
-
234
- ##### Returns
235
-
236
- - `Promise<IAudioMetadata>`:
237
-
238
- A promise that resolves to an `IAudioMetadata` object containing detailed metadata about the audio stream.
239
- This metadata includes information about the format, codec, duration, bitrate, and any embedded tags such as artist, album, or track information.
240
-
241
- ##### Usage Notes
242
- - This function is only available in Node.js environments, as it relies on the [Node.js stream API](https://nodejs.org/api/stream.html).
243
-
244
- ##### Example:
245
-
246
- The following example demonstrates how to use the `parseStream` function to read metadata from an audio stream:
247
- ```js
248
- import { parseStream } from 'music-metadata';
249
- import { createReadStream } from 'fs';
250
-
251
- (async () => {
252
- try {
253
- // Create a readable stream from a file
254
- const audioStream = createReadStream('path/to/audio/file.mp3');
255
-
256
- // Parse the metadata from the stream
257
- const metadata = await parseStream(audioStream, { mimeType: 'audio/mpeg'});
258
-
259
- // Log the parsed metadata
260
- console.log(metadata);
261
- } catch (error) {
262
- console.error('Error parsing metadata:', error.message);
263
- }
264
- })();
265
-
266
- ```
267
-
268
- ### Cross-platform functions
269
- These functions are designed to be cross-platform,
270
- meaning it can be used in both Node.js and web browsers.
271
-
272
- #### `parseWebStream` function
273
-
274
- The parseWebStream function is used to extract metadata from an audio track provided as a web-compatible ReadableStream.
275
- This function is ideal for applications running in web environments, such as browsers,
276
- where audio data is streamed over the network or read from other web-based sources.
277
-
278
-
279
- ##### Syntax
280
- ```ts
281
- parseWebStream(webStream: ReadableStream<Uint8Array>, fileInfo?: IFileInfo | string, options?: IOptions): Promise<IAudioMetadata>
282
- ```
283
-
284
- ##### Parameters
285
-
286
- - `webStream`: `ReadableStream<Uint8Array>`
287
-
288
- A [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) that provides the audio data to be parsed.
289
- This stream should emit Uint8Array chunks, representing the raw audio data.
290
-
291
- - `fileInfo`: `IFileInfo` (optional)
292
-
293
- An object containing file-related information or a string representing the MIME-type of the audio stream.
294
- The fileInfo parameter can help the parser to correctly identify the audio format and may include:
295
-
296
- - `mimeType`: A string representing the [MIME-type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) (e.g., `audio/mpeg`).
297
-
298
- If provided, it is assumed the streamed file content is to be the MIME-type.
299
- If not provided, the parser will attempt to determine the format based on the content of the stream.
300
-
301
- - `size`: The total size of the audio stream in bytes (useful for streams with a known length).
302
-
303
- - `path`: A string representing the file path or filename, which can also assist in determining the format.
304
-
305
- - `options`: `IOptions` (optional)
306
-
307
- An optional object containing additional parsing options.
308
- These options allow you to customize the parsing process,
309
- such as whether to calculate the duration or skip cover art extraction.
310
-
311
- ##### Returns
312
-
313
- - `Promise<IAudioMetadata>`:
314
-
315
- A promise that resolves to an `IAudioMetadata` object containing detailed metadata about the audio stream.
316
- This metadata includes information about the format, codec, duration, bitrate, and any embedded tags such as artist, album, or track information.
317
-
318
- ##### Example
319
- Here’s an example of how to use the `parseWebStream` function to extract metadata from an audio stream in a web application:
320
-
321
- ```js
322
- import { parseWebStream } from 'music-metadata';
323
-
324
- (async () => {
325
- try {
326
- // Assuming you have a ReadableStream of an audio file
327
- const response = await fetch('https://example.com/path/to/audio/file.mp3');
328
- const webStream = response.body;
329
-
330
- // Parse the metadata from the web stream
331
- const metadata = await parseWebStream(webStream, 'audio/mpeg');
332
-
333
- // Log the parsed metadata
334
- console.log(metadata);
335
- } catch (error) {
336
- console.error('Error parsing metadata:', error.message);
337
- }
338
- })();
339
- ```
340
-
341
- The example uses the [`fetch` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to retrieve an audio file from a URL.
342
- The `response.body` provides a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) that is then passed to `parseWebStream`.
343
-
344
- #### `parseBlob` function
345
-
346
- Parses metadata from an audio file represented as a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
347
- This function is suitable for use in environments that support the ReadableStreamBYOBReader, which is **available in Node.js 20** and above.
348
-
349
- ##### Syntax
350
- ```ts
351
- parseBlob(blob: Blob, options?: IOptions = {}): Promise<IAudioMetadata>
352
- ```
353
-
354
- ##### Parameters
355
-
356
- - `blob`: [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
357
-
358
- The Blob object containing the audio data to be parsed.
359
- This can be a file or any binary data. If the Blob is an instance of File, its name will be used as the file path in the metadata.
360
-
361
- - `options`: [IOptions](#ioptions-interface) (optional)
362
-
363
- An optional configuration object that specifies parsing options.
364
-
365
- ##### Returns
366
-
367
- - `Promise<IAudioMetadata>`:
368
-
369
- A promise that resolves to the metadata of the audio file.
370
-
371
- ##### Example
372
-
373
- ```js
374
- import { parseBlob } from 'music-metadata';
375
-
376
- (async () => {
377
- const fileInput = document.querySelector('input[type="file"]');
378
- const file = fileInput.files[0];
379
-
380
- try {
381
- const metadata = await parseBlob(file);
382
- console.log(metadata);
383
- } catch (error) {
384
- console.error('Error parsing metadata:', error.message);
385
- }
386
- })();
387
- ```
388
-
389
- #### `parseBuffer` function
390
-
391
- Parses metadata from an audio file where the audio data is held in a [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) or [Buffer](https://nodejs.org/api/buffer.html).
392
- This function is particularly useful when you already have audio data in memory.
393
-
394
- ##### Syntax
395
- ```ts
396
- parseBuffer(buffer: Uint8Array, fileInfo?: IFileInfo | string, opts?: IOptions = {}): Promise<IAudioMetadata>
397
- ```
398
-
399
- ##### Parameters
400
- - `uint8Array`: [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
401
-
402
- A [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) containing the audio data to be parsed.
403
-
404
- - `fileInfo`: `IFileInfo` | `string` (optional)
405
-
406
- An object containing file information such as mimeType and size.
407
- Alternatively, you can pass a MIME-type string directly.
408
- This helps the parser understand the format of the audio data.
409
-
410
- - `options`: [IOptions](#ioptions-interface) (optional)
411
-
412
- An optional configuration object that specifies parsing options.
413
-
414
- ##### Returns
415
- - `Promise<IAudioMetadata>`:
416
-
417
- A promise that resolves to the metadata of the audio file.
418
-
419
-
420
- ##### Example
421
-
422
- ```js
423
- import { parseBuffer } from 'music-metadata';
424
- import fs from 'fs';
425
-
426
- (async () => {
427
- const buffer = fs.readFileSync('path/to/audio/file.mp3');
428
-
429
- try {
430
- const metadata = await parseBuffer(buffer, { mimeType: 'audio/mpeg' });
431
- console.log(metadata);
432
- } catch (error) {
433
- console.error('Error parsing metadata:', error.message);
434
- }
435
- })();
436
- ```
437
-
438
- #### `parseFromTokenizer` function
439
- Parses metadata from an audio source that implements the [strtok3](https://github.com/Borewit/strtok3) ITokenizer interface.
440
- This is a low-level function that provides flexibility for advanced use cases,
441
- such as parsing metadata from streaming audio or custom data sources.
442
-
443
- This also enables special read modules like:
444
- - [streaming-http-token-reader](https://github.com/Borewit/streaming-http-token-reader) for chunked HTTP(S) reading, using [HTTP range requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests).
445
-
446
- ##### Syntax
447
- ```ts
448
- parseFromTokenizer(tokenizer: ITokenizer, options?: IOptions): Promise<IAudioMetadata>
449
- ```
450
-
451
- ##### Parameters
452
- - `tokenizer: ITokenizer`
453
-
454
- An instance of an ITokenizer that provides access to the audio data.
455
- The tokenizer abstracts the reading process, enabling support for various types of sources, including streams, buffers, or custom data readers.
456
-
457
- - `options`: [IOptions](#ioptions-interface) (optional)
458
-
459
- An optional configuration object that specifies parsing options.
460
-
461
- ##### Returns
462
- - `Promise<IAudioMetadata>`:
463
-
464
- A promise that resolves to the metadata of the audio source, including information like the title, artist, album, and more.
465
-
466
-
467
- ##### Example
468
- ````js
469
- import { fromNodeProviderChain } from '@aws-sdk/credential-providers';
470
- import { S3Client } from '@aws-sdk/client-s3';
471
- import { makeTokenizer } from '@tokenizer/s3';
472
- import { parseFromTokenizer as mmParseFromTokenizer } from 'music-metadata';
473
-
474
- // Configure the S3 client
475
- const s3 = new S3Client({
476
- region: 'eu-west-2',
477
- credentials: fromNodeProviderChain(),
478
- });
479
-
480
- // Helper function to create a tokenizer for S3 objects
481
- async function makeS3TestDataTokenizer(key, options) {
482
- return await makeTokenizer(s3, {
483
- Bucket: 'music-metadata',
484
- Key: key,
485
- }, options);
486
- }
487
-
488
- // Function to read and log metadata from an S3 object
489
- async function readMetadata() {
490
- try {
491
- // Create a tokenizer for the specified S3 object
492
- const tokenizer = await makeS3TestDataTokenizer('path/to/audio/file.mp3', { disableChunked: false });
493
-
494
- // Parse the metadata from the tokenizer
495
- const metadata = await mmParseFromTokenizer(tokenizer);
496
-
497
- // Log the retrieved metadata
498
- console.log(metadata);
499
- } catch (error) {
500
- console.error('Error parsing metadata:', error.message);
501
- }
502
- }
503
-
504
- // Execute the metadata reading function
505
- readMetadata();
506
- ````
507
- ##### Additional Resources
508
- - [strtok3](https://github.com/Borewit/strtok3) - Learn more about the `ITokenizer` interface and how to implement it for various use cases.
509
- - [AWS SDK for JavaScript](https://aws.amazon.com/sdk-for-javascript/) - Documentation on using the AWS SDK to interact with S3 and other AWS services.
510
- - [@tokenizer/s3](https://github.com/Borewit/tokenizer-s3) - Example of `ITokenizer` implementation.
511
-
512
- ### Handling Parse Errors
513
-
514
- `music-metadata` provides a robust and extensible error handling system with custom error classes that inherit from the standard JavaScript `Error`.
515
- All possible parsing errors are part of a union type `UnionOfParseErrors`, ensuring that every error scenario is accounted for in your code.
516
-
517
- #### Union of Parse Errors
518
-
519
- All parsing errors extend from the base class `ParseError` and are included in the `UnionOfParseErrors` type:
520
- ```ts
521
- export type UnionOfParseErrors =
522
- | CouldNotDetermineFileTypeError
523
- | UnsupportedFileTypeError
524
- | UnexpectedFileContentError
525
- | FieldDecodingError
526
- | InternalParserError;
527
- ```
528
-
529
- #### Error Types
530
-
531
- - `CouldNotDetermineFileTypeError`: Raised when the file type cannot be determined.
532
- - `UnsupportedFileTypeError`: Raised when an unsupported file type is encountered.
533
- - `UnexpectedFileContentError`: Raised when the file content does not match the expected format.
534
- - `FieldDecodingError`: Raised when a specific field in the file cannot be decoded.
535
- - `InternalParserError`: Raised for internal parser errors.
536
-
537
- ### Other functions
538
-
539
- #### `orderTags` function
540
-
541
- Utility to Converts the native tags to a dictionary index on the tag identifier
542
-
543
- ```ts
544
- orderTags(nativeTags: ITag[]): [tagId: string]: any[]
545
- ```
546
-
547
- ```js
548
- import { parseFile, orderTags } from 'music-metadata';
549
- import { inspect } from 'util';
550
-
551
- (async () => {
552
- try {
553
- const metadata = await parseFile('../test/samples/MusicBrainz - Beth Hart - Sinner\'s Prayer [id3v2.3].V2.mp3');
554
- const orderedTags = orderTags(metadata.native['ID3v2.3']);
555
- console.log(inspect(orderedTags, { showHidden: false, depth: null }));
556
- } catch (error) {
557
- console.error(error.message);
558
- }
559
- })();
560
- ```
561
-
562
- #### `ratingToStars` function
563
-
564
- 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.
565
-
566
- ```ts
567
- ratingToStars(rating: number): number
568
- ```
569
- #### `selectCover` function
570
-
571
- Select cover image based on image type field, otherwise the first picture in file.
572
-
573
- ```ts
574
- export function selectCover(pictures?: IPicture[]): IPicture | null
575
- ```
576
-
577
- ```js
578
- import { parseFile, selectCover } from 'music-metadata';
579
-
580
- (async () => {
581
- const {common} = await parseFile(filePath);
582
- const cover = selectCover(common.picture); // pick the cover image
583
- }
584
- )();
585
- ```
586
-
587
- ### `IOptions` Interface
588
- - `duration`: `boolean` (default: `false`)
589
-
590
- If set to `true`, the parser will analyze the entire media file, if necessary, to determine its duration.
591
- This option ensures accurate duration calculation but may increase processing time for large files.
592
-
593
- - `observer`: `(update: MetadataEvent) => void;`:
594
-
595
- A callback function that is invoked whenever there is an update to the common (generic) tag or format properties during parsing.
596
- This allows for real-time updates on metadata changes.
597
-
598
- - `skipCovers`: `boolean` (default: `false`)
599
-
600
- If set to `true`, the parser will skip the extraction of embedded cover art (images) from the media file.
601
- This can be useful to avoid processing unnecessary data if cover images are not required.
602
-
603
- - `mkvUseIndex`: `boolean` (default: `false`)
604
-
605
- If set to true, the parser will use the SeekHead element index to skip segment/cluster elements in Matroska-based files. This is an experimental feature and can significantly impact performance. It may also result in some metadata being skipped if it is not indexed.
606
- If the SeekHead element is absent in the Matroska file, this flag has no effect.
607
-
608
- > [!NOTE]
609
- > - The `duration` option is typically included in most cases, but setting it to true ensures that the entire file is parsed if necessary to get an accurate duration.
610
- > - Using `mkvUseIndex` can improve performance in Matroska files, but be aware of potential side effects, such as missing metadata due to skipped elements.
611
-
612
-
613
- ### `IAudioMetadata` interface
614
-
615
- If the returned promise resolves, the metadata (TypeScript `IAudioMetadata` interface) contains:
616
- - [`metadata.format`](#metadataformat) Audio format information
617
- - [`metadata.common`](#metadatacommon) Is a generic (abstract) way of reading metadata information.
618
- - [`metadata.trackInfo`](#metadatatrackInfo) Is a generic (abstract) way of reading metadata information.
619
- - `metadata.native` List of native (original) tags found in the parsed audio file.
620
-
621
- #### `metadata.format`
622
-
623
- The questionmark `?` indicates the property is optional.
624
-
625
- Audio format information. Defined in the TypeScript `IFormat` interface:
626
- - `format.container?: string` Audio encoding format. e.g.: 'flac'
627
- - `format.codec?` Name of the codec (algorithm used for the audio compression)
628
- - `format.codecProfile?: string` Codec profile / settings
629
- - `format.tagTypes?: TagType[]` List of tagging formats found in parsed audio file
630
- - `format.duration?: number` Duration in seconds
631
- - `format.bitrate?: number` Number bits per second of encoded audio file
632
- - `format.sampleRate?: number` Sampling rate in Samples per second (S/s)
633
- - `format.bitsPerSample?: number` Audio bit depth
634
- - `format.lossless?: boolean` True if lossless, false for lossy encoding
635
- - `format.numberOfChannels?: number` Number of audio channels
636
- - `format.creationTime?: Date` Track creation time
637
- - `format.modificationTime?: Date` Track modification / tag update time
638
- - `format.trackGain?: number` Track gain in dB
639
- - `format.albumGain?: number` Album gain in dB
640
-
641
- #### `metadata.trackInfo`
642
-
643
- To support advanced containers like [Matroska](https://wikipedia.org/wiki/Matroska) or [MPEG-4](https://en.wikipedia.org/wiki/MPEG-4), which may contain multiple audio and video tracks, the **experimental**- `metadata.trackInfo` has been added,
644
-
645
- `metadata.trackInfo` is either `undefined` or has an **array** of [trackInfo](#trackinfo)
646
-
647
- ##### trackInfo
648
-
649
- Audio format information. Defined in the TypeScript `IFormat` interface:
650
- - `trackInfo.type?: TrackType` Track type
651
- - `trackInfo.codecName?: string` Codec name
652
- - `trackInfo.codecSettings?: string` Codec settings
653
- - `trackInfo.flagEnabled?: boolean` Set if the track is usable, default: `true`
654
- - `trackInfo.flagDefault?: boolean` Set if that track (audio, video or subs) SHOULD be active if no language found matches the user preference.
655
- - `trackInfo.flagLacing?: boolean` Set if the track **may** contain blocks using lacing
656
- - `trackInfo.name?: string` A human-readable track name.
657
- - `trackInfo.language?: string` Specifies the language of the track
658
- - `trackInfo.audio?: IAudioTrack`, see [`trackInfo.audioTrack`](#trackinfoaudiotrack)
659
- - `trackInfo.video?: IVideoTrack`, see [`trackInfo.videoTrack`](#trackinfovideotrack)
660
-
661
- ##### `trackInfo.audioTrack`
662
-
663
- - `audioTrack.samplingFrequency?: number`
664
- - `audioTrack.outputSamplingFrequency?: number`
665
- - `audioTrack.channels?: number`
666
- - `audioTrack.channelPositions?: Buffer`
667
- - `audioTrack.bitDepth?: number`
668
-
669
- ##### `trackInfo.videoTrack`
670
-
671
- - `videoTrack.flagInterlaced?: boolean`
672
- - `videoTrack.stereoMode?: number`
673
- - `videoTrack.pixelWidth?: number`
674
- - `videoTrack.pixelHeight?: number`
675
- - `videoTrack.displayWidth?: number`
676
- - `videoTrack.displayHeight?: number`
677
- - `videoTrack.displayUnit?: number`
678
- - `videoTrack.aspectRatioType?: number`
679
- - `videoTrack.colourSpace?: Buffer`
680
- - `videoTrack.gammaValue?: number`
681
-
682
- #### `metadata.common`
683
-
684
- [Common tag documentation](doc/common_metadata.md) is automatically generated.
685
-
686
- ## Examples
687
-
688
- 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.
689
- ```js
690
- import { parseStream } from 'music-metadata';
691
- import { inspect } from 'util';
692
-
693
- (async () => {
694
- const metadata = await parseStream(someReadStream, {mimeType: 'audio/mpeg', size: 26838}, {duration: true});
695
- console.log(inspect(metadata, {showHidden: false, depth: null}));
696
- someReadStream.close();
697
- }
698
- )();
699
- ```
700
-
701
- ### Access cover art
702
-
703
- Via `metadata.common.picture` you can access an array of cover art if present.
704
- Each picture has this interface:
705
-
706
- ```ts
707
- /**
708
- * Attached picture, typically used for cover art
709
- */
710
- export interface IPicture {
711
- /**
712
- * Image mime type
713
- */
714
- format: string;
715
- /**
716
- * Image data
717
- */
718
- data: Buffer;
719
- /**
720
- * Optional description
721
- */
722
- description?: string;
723
- /**
724
- * Picture type
725
- */
726
- type?: string;
727
- }
728
- ```
729
-
730
- To assign `img` HTML-object you can do something like:
731
- ```js
732
- import {uint8ArrayToBase64} from 'uint8array-extras';
733
-
734
- img.src = `data:${picture.format};base64,${uint8ArrayToBase64(picture.data)}`;
735
- ```
736
-
737
- ## Dependencies
738
-
739
- Dependency diagram:
740
- ```mermaid
741
- graph TD;
742
- MMN("music-metadata (Node.js entry point)")-->MMP
743
- MMN-->FTN
744
- MMP("music-metadata (primary entry point)")-->S(strtok3)
745
- MMP-->TY(token-types)
746
- MMP-->FTP
747
- MMP-->UAE
748
- FTN("file-type (Node.js entry point)")-->FTP
749
- FTP("file-type (primary entry point)")-->S
750
- S(strtok3)-->P(peek-readable)
751
- S(strtok3)-->TO("@tokenizer/token")
752
- TY(token-types)-->TO
753
- TY-->IE("ieee754")
754
- FTP-->TY
755
- NS("node:stream")
756
- FTN-->NS
757
- FTP-->UAE(uint8array-extras)
758
- style NS fill:#F88,stroke:#A44
759
- style IE fill:#CCC,stroke:#888
760
- style FTN fill:#FAA,stroke:#A44
761
- style MMN fill:#FAA,stroke:#A44
762
- ```
763
-
764
- Dependency list:
765
- - [tokenizer-token](https://github.com/Borewit/tokenizer-token)
766
- - [strtok3](https://github.com/Borewit/strtok3)
767
- - [token-types](https://github.com/Borewit/token-types)
768
- - [file-type](https://github.com/sindresorhus/file-type)
769
- - [@tokenizer-token](https://github.com/Borewit/tokenizer-token)
770
- - [peek-readable](https://github.com/Borewit/peek-readable)
771
-
772
- ## CommonJS backward compatibility
773
-
774
- For legacy CommonJS projects needing to load the `music-metadata` ESM module, you can use the `loadMusicMetadata` function:
775
- ```js
776
- const { loadMusicMetadata } = require('music-metadata');
777
-
778
- (async () => {
779
- // Dynamically loads the ESM module in a CommonJS project
780
- const mm = await loadMusicMetadata();
781
-
782
- const metadata = await mm.parseFile('/path/to/your/file');
783
- })();
784
-
785
- ```
786
-
787
- > [!NOTE]
788
- > The `loadMusicMetadata` function is experimental.
789
-
790
- ## Frequently Asked Questions
791
-
792
- ### How can I traverse (a long) list of files?
793
-
794
- What is important that file parsing should be done in a sequential manner.
795
- 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.
796
- There are multiple ways of achieving this:
797
-
798
- 1. Using recursion
799
-
800
- ```js
801
- import { parseFile } from 'music-metadata';
802
-
803
- function parseFiles(audioFiles) {
804
-
805
- const audioFile = audioFiles.shift();
806
-
807
- if (audioFile) {
808
- return parseFile(audioFile).then(metadata => {
809
- // Do great things with the metadata
810
- return parseFiles(audioFiles); // process rest of the files AFTER we are finished
811
- })
812
- }
813
- }
814
-
815
- ```
816
-
817
- 1. Use async/await
818
-
819
- Use [async/await](https://javascript.info/async-await)
820
-
821
- ```js
822
- import { parseFile } from 'music-metadata';
823
-
824
- // it is required to declare the function 'async' to allow the use of await
825
- async function parseFiles(audioFiles) {
826
-
827
- for (const audioFile of audioFiles) {
828
-
829
- // await will ensure the metadata parsing is completed before we move on to the next file
830
- const metadata = await parseFile(audioFile);
831
- // Do great things with the metadata
832
- }
833
- }
834
- ```
835
-
836
- ## Licence
837
-
838
- The MIT License (MIT)
839
-
840
- Copyright © 2024 Borewit
841
-
842
- 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:
843
-
844
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
845
-
846
- 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.
1
+ [![Node.js CI](https://github.com/Borewit/music-metadata/actions/workflows/nodejs-ci.yml/badge.svg?branch=master)](https://github.com/Borewit/music-metadata/actions?query=branch%3Amaster)
2
+ [![NPM version](https://img.shields.io/npm/v/music-metadata.svg)](https://npmjs.org/package/music-metadata)
3
+ [![npm downloads](http://img.shields.io/npm/dm/music-metadata.svg)](https://npmcharts.com/compare/music-metadata,jsmediatags,musicmetadata,node-id3,mp3-parser,id3-parser,wav-file-info?start=600&interval=30)
4
+ [![Coverage Status](https://coveralls.io/repos/github/Borewit/music-metadata/badge.svg?branch=master)](https://coveralls.io/github/Borewit/music-metadata?branch=master)
5
+ [![Codacy Badge](https://api.codacy.com/project/badge/Grade/57d731b05c9e41889a2a17cb4b0384d7)](https://app.codacy.com/app/Borewit/music-metadata?utm_source=github.com&utm_medium=referral&utm_content=Borewit/music-metadata&utm_campaign=Badge_Grade_Dashboard)
6
+ [![CodeQL](https://github.com/Borewit/music-metadata/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/Borewit/music-metadata/actions/workflows/codeql-analysis.yml)
7
+ [![DeepScan grade](https://deepscan.io/api/teams/5165/projects/6938/branches/61821/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=5165&pid=6938&bid=61821)
8
+ [![Known Vulnerabilities](https://snyk.io/test/github/Borewit/music-metadata/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/music-metadata?targetFile=package.json)
9
+ [![Discord](https://img.shields.io/discord/460524735235883049.svg)](https://discord.gg/KyBr6sb)
10
+
11
+ # music-metadata
12
+
13
+ Key features:
14
+ - **Comprehensive Format Support**: Supports popular audio formats like MP3, MP4, FLAC, Ogg, WAV, AIFF, and more.
15
+ - **Extensive Metadata Extraction**: Extracts detailed metadata, including ID3v1, ID3v2, APE, Vorbis, and iTunes/MP4 tags.
16
+ - **Streaming Support**: Efficiently handles large audio files by reading metadata from streams, making it suitable for server-side and browser-based applications.
17
+ - **Promise-Based API**: Provides a modern, promise-based API for easy integration into asynchronous workflows.
18
+ - **Cross-Platform**: Works in both [Node.js](https://nodejs.org/) and browser environments with the help of bundlers like [Webpack](https://webpack.js.org/) or [Rollup](https://rollupjs.org/introduction/).
19
+
20
+ The [`music-metadata`](https://github.com/Borewit/music-metadata) module is ideal for developers working on media applications, music players, or any project that requires access to detailed audio file metadata.
21
+
22
+ ## Compatibility
23
+
24
+ Module: version 8 migrated from [CommonJS](https://en.wikipedia.org/wiki/CommonJS) to [pure ECMAScript Module (ESM)](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).
25
+ The distributed JavaScript codebase is compliant with the [ECMAScript 2020 (11th Edition)](https://en.wikipedia.org/wiki/ECMAScript_version_history#11th_Edition_%E2%80%93_ECMAScript_2020) standard.
26
+
27
+ > [!NOTE]
28
+ > See also [CommonJS backward Compatibility](#commonjs-backward-compatibility)
29
+
30
+ This module requires a [Node.js ≥ 16](https://nodejs.org/en/about/previous-releases) engine.
31
+ It can also be used in a browser environment when bundled with a module bundler.
32
+
33
+ ## Support the Project
34
+ If you find this project useful and would like to support its development, consider sponsoring or contributing:
35
+
36
+ - [Become a sponsor to Borewit](https://github.com/sponsors/Borewit)
37
+
38
+ - Buy me a coffee:
39
+
40
+ <a href="https://www.buymeacoffee.com/borewit" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy me A coffee" height="41" width="174"></a>
41
+
42
+ ## Features
43
+
44
+ ### Support for audio file types
45
+
46
+ | Audio format | Description | Wiki | |
47
+ | ------------- |---------------------------------| -------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------:|
48
+ | AIFF / AIFF-C | Audio Interchange File Format | [:link:](https://wikipedia.org/wiki/Audio_Interchange_File_Format) | <img src="https://upload.wikimedia.org/wikipedia/commons/8/84/Apple_Computer_Logo_rainbow.svg" width="40" alt="Apple rainbow logo"> |
49
+ | AAC | ADTS / Advanced Audio Coding | [:link:](https://en.wikipedia.org/wiki/Advanced_Audio_Coding) | <img src="https://svgshare.com/i/UT8.svg" width="40" alt="AAC logo"> |
50
+ | APE | Monkey's Audio | [:link:](https://wikipedia.org/wiki/Monkey's_Audio) | <img src="https://foreverhits.files.wordpress.com/2015/05/ape_audio.jpg" width="40" alt="Monkey's Audio logo"> |
51
+ | ASF | Advanced Systems Format | [:link:](https://wikipedia.org/wiki/Advanced_Systems_Format) | |
52
+ | BWF | Broadcast Wave Format | [:link:](https://en.wikipedia.org/wiki/Broadcast_Wave_Format) | |
53
+ | DSDIFF | Philips DSDIFF | [:link:](https://wikipedia.org/wiki/Direct_Stream_Digital) | <img src="https://upload.wikimedia.org/wikipedia/commons/b/bc/DSDlogo.svg" width="80" alt="DSD logo"> |
54
+ | DSF | Sony's DSD Stream File | [:link:](https://wikipedia.org/wiki/Direct_Stream_Digital) | <img src="https://upload.wikimedia.org/wikipedia/commons/b/bc/DSDlogo.svg" width="80" alt="DSD logo"> |
55
+ | FLAC | Free Lossless Audio Codec | [:link:](https://wikipedia.org/wiki/FLAC) | <img src="https://upload.wikimedia.org/wikipedia/commons/a/a2/FLAC_logo_vector.svg" width="80" alt="FLAC logo"> |
56
+ | MP2 | MPEG-1 Audio Layer II | [:link:](https://wikipedia.org/wiki/MPEG-1_Audio_Layer_II) | |
57
+ | Matroska | Matroska (EBML), mka, mkv | [:link:](https://wikipedia.org/wiki/Matroska) | <img src="https://upload.wikimedia.org/wikipedia/commons/1/1a/Matroska_2010.svg" width="80" alt="Matroska logo"> |
58
+ | MP3 | MPEG-1 / MPEG-2 Audio Layer III | [:link:](https://wikipedia.org/wiki/MP3) | <img src="https://upload.wikimedia.org/wikipedia/commons/e/ea/Mp3.svg" width="80" alt="MP3 logo"> |
59
+ | MPC | Musepack SV7 | [:link:](https://wikipedia.org/wiki/Musepack) | <img src="https://www.musepack.net/pictures/musepack_logo.png" width="80" alt="musepack logo"> |
60
+ | MPEG 4 | mp4, m4a, m4v | [:link:](https://wikipedia.org/wiki/MPEG-4) | <img src="https://svgshare.com/i/UU3.svg" width="80" alt="mpeg 4 logo"> |
61
+ | Ogg | Open container format | [:link:](https://en.wikipedia.org/wiki/Ogg) | <img src="https://upload.wikimedia.org/wikipedia/commons/a/a1/Ogg_Logo.svg" width="80" alt="Ogg logo"> |
62
+ | Opus | | [:link:](https://wikipedia.org/wiki/Opus_(audio_format)) | <img src="https://upload.wikimedia.org/wikipedia/commons/0/02/Opus_logo2.svg" width="80" alt="Opus logo"> |
63
+ | Speex | | [:link:](https://wikipedia.org/wiki/Speex) | <img src="https://upload.wikimedia.org/wikipedia/commons/b/b5/Speex_logo_2006.svg" width="80" alt="Speex logo"> |
64
+ | Theora | | [:link:](https://en.wikipedia.org/wiki/Theora) | <img src="https://upload.wikimedia.org/wikipedia/commons/5/57/Theora_logo_2007.svg" width="70" alt="Theora logo"> |
65
+ | Vorbis | Vorbis audio compression | [:link:](https://wikipedia.org/wiki/Ogg_Vorbis) | <img src="https://upload.wikimedia.org/wikipedia/commons/8/8d/Xiph.Org_logo_square.svg" width="70" alt="Vorbis logo"> |
66
+ | WAV | RIFF WAVE | [:link:](https://wikipedia.org/wiki/WAV) | |
67
+ | WebM | webm | [:link:](https://wikipedia.org/wiki/WebM) | <img src="https://upload.wikimedia.org/wikipedia/commons/3/34/WebM_logo.svg" width="80" alt="Matroska logo"> |
68
+ | WV | WavPack | [:link:](https://wikipedia.org/wiki/WavPack) | <img src="http://www.wavpack.com/wavpacklogo.svg" width="60" alt="WavPack logo"> |
69
+ | WMA | Windows Media Audio | [:link:](https://wikipedia.org/wiki/Windows_Media_Audio) | <img src="https://upload.wikimedia.org/wikipedia/commons/7/76/Windows_Media_Player_simplified_logo.svg" width="40" alt="Windows Media logo"> |
70
+
71
+ ### Supported tag headers
72
+
73
+ Following tag header formats are supported:
74
+ - [APE](https://wikipedia.org/wiki/APE_tag)
75
+ - [ASF](https://wikipedia.org/wiki/Advanced_Systems_Format)
76
+ - EXIF 2.3
77
+ - [ID3](https://wikipedia.org/wiki/ID3): ID3v1, ID3v1.1, ID3v2.2, [ID3v2.3](http://id3.org/id3v2.3.0) & [ID3v2.4](http://id3.org/id3v2.4.0-frames)
78
+ - [iTunes](https://github.com/sergiomb2/libmp4v2/wiki/iTunesMetadata)
79
+ - [RIFF](https://wikipedia.org/wiki/Resource_Interchange_File_Format)/INFO
80
+ - [Vorbis comment](https://wikipedia.org/wiki/Vorbis_comment)
81
+ - [AIFF](https://wikipedia.org/wiki/Audio_Interchange_File_Format)
82
+
83
+ Following lyric formats are supported:
84
+ - [LRC](https://en.wikipedia.org/wiki/LRC_(file_format))
85
+ - Synchronized lyrics (SYLT)
86
+ - Unsynchronized lyrics (USULT)
87
+
88
+ Support for [MusicBrainz](https://musicbrainz.org/) tags as written by [Picard](https://picard.musicbrainz.org/).
89
+ [ReplayGain](https://wiki.hydrogenaud.io/index.php?title=ReplayGain) tags are supported.
90
+
91
+ ### Audio format & encoding details
92
+
93
+ Support for encoding / format details:
94
+ - [Bit rate](https://wikipedia.org/wiki/Bit_rate)
95
+ - [Audio bit depth](https://wikipedia.org/wiki/Audio_bit_depth)
96
+ - Duration
97
+ - Encoding profile (e.g. [CBR](https://en.wikipedia.org/wiki/Constant_bitrate), V0, V2)
98
+
99
+
100
+ ## Online demo's
101
+ - [<img src="https://raw.githubusercontent.com/Borewit/audio-tag-analyzer/master/src/assets/icon/audio-tag-analyzer.svg" width="40">Audio Tag Analyzer](https://audio-tag-analyzer.netlify.app/)
102
+ - [<img src="https://cdn.sanity.io/images/3do82whm/next/ba8c847f13a5fa39d88f8bc9b7846b7886531b18-2500x2500.svg" width="40"> Webamp](https://webamp.org/)
103
+ - Expected to be released soon: [Overtone](https://overtone.pro/) by [Johannes Schickling](https://github.com/schickling)
104
+
105
+ ## Usage
106
+
107
+ ### Installation
108
+ Install using [npm](http://npmjs.org/):
109
+
110
+ ```bash
111
+ npm install music-metadata
112
+ ```
113
+ or using [yarn](https://yarnpkg.com/):
114
+ ```bash
115
+ yarn add music-metadata
116
+ ```
117
+
118
+ ## API Documentation
119
+
120
+ ### Overview
121
+
122
+ **Node.js specific** functions to read an audio file or stream:
123
+ 1. **File Parsing**: Parse audio files directly from the filesystem using the [parseFile function](#parsefile-function)
124
+ 1. **Stream Parsing**: Parse audio metadata from a Node.js [Readable stream](https://nodejs.org/api/stream.html#class-streamreadable) using the [parseStream function](#parsewebstream-function).
125
+
126
+ **Cross-platform** functions available to read an audio file or stream:
127
+
128
+ There are multiple ways to parse (read) audio tracks:
129
+ 1. **Web Stream Parsing**: Parse audio data from a web-compatible [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) using the [parseWebStream function](#parsewebstream-function).
130
+ 1. **Blob Parsing**: Parse audio metadata from a (Web API) [Blob](https://developer.mozilla.org/docs/Web/API/Blob) or [File](https://developer.mozilla.org/docs/Web/API/File) using the [parseBlob function](#parseblob-function).
131
+ 1. **Buffer Parsing**: Parse audio metadata from a [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) or [Buffer](https://nodejs.org/api/buffer.html) using the [parseBuffer function](#parsebuffer-function).
132
+ 1. **Tokenizer Parsing:** Use a custom or third-party [strtok3](https://github.com/Borewit/strtok3) `ITokenizer` to parse using the [parseFromTokenizer function](#parsefromtokenizer-function).
133
+
134
+ > [!NOTE]
135
+ > Direct file access in Node.js is generally faster because it can 'jump' to various parts of the file without reading intermediate data.
136
+
137
+ ### Node.js specific function
138
+ These functions are tailored for Node.js environments and leverage Node.js-specific APIs,
139
+ making them incompatible with browser-based JavaScript engines.
140
+
141
+ #### `parseFile` function
142
+
143
+ The `parseFile` function is intended for extracting metadata from audio files on the local filesystem in a Node.js environment.
144
+ It reads the specified file, parses its audio metadata, and returns a promise that resolves with this information.
145
+
146
+ ##### Syntax
147
+ ```ts
148
+ parseFile(filePath: string, options?: IOptions): Promise<IAudioMetadata>
149
+ ```
150
+
151
+ ##### Parameters
152
+
153
+ - `filePath`: `string`
154
+
155
+ The path to the media file from which metadata should be extracted.
156
+ This should be a valid path to an audio file on the local filesystem.
157
+
158
+ - `options`: [IOptions](#ioptions-interface) (optional)
159
+
160
+ An optional configuration object that allows customization of the parsing process.
161
+ These options can include whether to calculate the file's duration, skip embedded cover art,
162
+ or other parsing behaviors.
163
+
164
+ ##### Returns
165
+
166
+ - `Promise<IAudioMetadata>`:
167
+
168
+ A promise that resolves to an IAudioMetadata object containing metadata about the audio file.
169
+ The metadata includes details such as the file format, codec, duration, bit rate, and any embedded tags like album, artist, or track information.
170
+
171
+ ##### Usage Notes
172
+
173
+ - This function is **Node.js-only** and relies on Node.js-specific APIs to access the filesystem.
174
+
175
+ - For browser environments, consider using the [parseBlob](#parseblob-function) to parse [File object](https://developer.mozilla.org/en-US/docs/Web/API/File) objects.
176
+
177
+ ##### Example:
178
+
179
+ The following example demonstrates how to use the parseFile function to read metadata from an audio file:
180
+ ```js
181
+ import { parseFile } from 'music-metadata';
182
+ import { inspect } from 'util';
183
+
184
+ (async () => {
185
+ try {
186
+ const filePath = '../music-metadata/test/samples/MusicBrainz - Beth Hart - Sinner\'s Prayer [id3v2.3].V2.mp3';
187
+ const metadata = await parseFile(filePath);
188
+
189
+ // Output the parsed metadata to the console in a readable format
190
+ console.log(inspect(metadata, { showHidden: false, depth: null }));
191
+ } catch (error) {
192
+ console.error('Error parsing metadata:', error.message);
193
+ }
194
+ })();
195
+ ```
196
+
197
+ #### `parseStream` function
198
+
199
+ The parseStream function is used to parse metadata from an audio track provided as a Node.js [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) stream.
200
+ This is particularly useful for processing audio data that is being streamed or piped from another source, such as a web server or file system.
201
+
202
+ ##### Syntax:
203
+ ```ts
204
+ parseStream(stream: Readable, fileInfo?: IFileInfo | string, options?: IOptions): Promise<IAudioMetadata>
205
+ ```
206
+
207
+ ##### Parameters:
208
+
209
+ - `stream`: `Readable`:
210
+
211
+ The Node.js [Readable](https://nodejs.org/api/stream.html#class-streamreadable) stream from which the audio data is read.
212
+ This stream should provide the raw audio data to be analyzed.
213
+
214
+ - `fileInfo`: `IFileInfo` (optional)
215
+
216
+ An object containing file-related information or a string representing the MIME-type of the audio stream.
217
+ The fileInfo parameter can help the parser to correctly identify the audio format and may include:
218
+
219
+ - `mimeType`: A string representing the [MIME-type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) (e.g., `audio/mpeg`).
220
+
221
+ If provided, it is assumed the streamed file content is to be the MIME-type.
222
+ If not provided, the parser will attempt to determine the format based on the content of the stream.
223
+
224
+ - `size`: The total size of the audio stream in bytes (useful for streams with a known length).
225
+
226
+ - `path`: A string representing the file path or filename, which can also assist in determining the format.
227
+
228
+ - `options`: `IOptions` (optional)
229
+
230
+ An optional object containing additional parsing options.
231
+ These options allow you to customize the parsing process,
232
+ such as whether to calculate the duration or skip cover art extraction.
233
+
234
+ ##### Returns
235
+
236
+ - `Promise<IAudioMetadata>`:
237
+
238
+ A promise that resolves to an `IAudioMetadata` object containing detailed metadata about the audio stream.
239
+ This metadata includes information about the format, codec, duration, bitrate, and any embedded tags such as artist, album, or track information.
240
+
241
+ ##### Usage Notes
242
+ - This function is only available in Node.js environments, as it relies on the [Node.js stream API](https://nodejs.org/api/stream.html).
243
+
244
+ ##### Example:
245
+
246
+ The following example demonstrates how to use the `parseStream` function to read metadata from an audio stream:
247
+ ```js
248
+ import { parseStream } from 'music-metadata';
249
+ import { createReadStream } from 'fs';
250
+
251
+ (async () => {
252
+ try {
253
+ // Create a readable stream from a file
254
+ const audioStream = createReadStream('path/to/audio/file.mp3');
255
+
256
+ // Parse the metadata from the stream
257
+ const metadata = await parseStream(audioStream, { mimeType: 'audio/mpeg'});
258
+
259
+ // Log the parsed metadata
260
+ console.log(metadata);
261
+ } catch (error) {
262
+ console.error('Error parsing metadata:', error.message);
263
+ }
264
+ })();
265
+
266
+ ```
267
+
268
+ ### Cross-platform functions
269
+ These functions are designed to be cross-platform,
270
+ meaning it can be used in both Node.js and web browsers.
271
+
272
+ #### `parseWebStream` function
273
+
274
+ The parseWebStream function is used to extract metadata from an audio track provided as a web-compatible ReadableStream.
275
+ This function is ideal for applications running in web environments, such as browsers,
276
+ where audio data is streamed over the network or read from other web-based sources.
277
+
278
+
279
+ ##### Syntax
280
+ ```ts
281
+ parseWebStream(webStream: ReadableStream<Uint8Array>, fileInfo?: IFileInfo | string, options?: IOptions): Promise<IAudioMetadata>
282
+ ```
283
+
284
+ ##### Parameters
285
+
286
+ - `webStream`: `ReadableStream<Uint8Array>`
287
+
288
+ A [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) that provides the audio data to be parsed.
289
+ This stream should emit Uint8Array chunks, representing the raw audio data.
290
+
291
+ - `fileInfo`: `IFileInfo` (optional)
292
+
293
+ An object containing file-related information or a string representing the MIME-type of the audio stream.
294
+ The fileInfo parameter can help the parser to correctly identify the audio format and may include:
295
+
296
+ - `mimeType`: A string representing the [MIME-type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) (e.g., `audio/mpeg`).
297
+
298
+ If provided, it is assumed the streamed file content is to be the MIME-type.
299
+ If not provided, the parser will attempt to determine the format based on the content of the stream.
300
+
301
+ - `size`: The total size of the audio stream in bytes (useful for streams with a known length).
302
+
303
+ - `path`: A string representing the file path or filename, which can also assist in determining the format.
304
+
305
+ - `options`: `IOptions` (optional)
306
+
307
+ An optional object containing additional parsing options.
308
+ These options allow you to customize the parsing process,
309
+ such as whether to calculate the duration or skip cover art extraction.
310
+
311
+ ##### Returns
312
+
313
+ - `Promise<IAudioMetadata>`:
314
+
315
+ A promise that resolves to an `IAudioMetadata` object containing detailed metadata about the audio stream.
316
+ This metadata includes information about the format, codec, duration, bitrate, and any embedded tags such as artist, album, or track information.
317
+
318
+ ##### Example
319
+ Here’s an example of how to use the `parseWebStream` function to extract metadata from an audio stream in a web application:
320
+
321
+ ```js
322
+ import { parseWebStream } from 'music-metadata';
323
+
324
+ (async () => {
325
+ try {
326
+ // Assuming you have a ReadableStream of an audio file
327
+ const response = await fetch('https://example.com/path/to/audio/file.mp3');
328
+ const webStream = response.body;
329
+
330
+ // Parse the metadata from the web stream
331
+ const metadata = await parseWebStream(webStream, 'audio/mpeg');
332
+
333
+ // Log the parsed metadata
334
+ console.log(metadata);
335
+ } catch (error) {
336
+ console.error('Error parsing metadata:', error.message);
337
+ }
338
+ })();
339
+ ```
340
+
341
+ The example uses the [`fetch` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to retrieve an audio file from a URL.
342
+ The `response.body` provides a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) that is then passed to `parseWebStream`.
343
+
344
+ #### `parseBlob` function
345
+
346
+ Parses metadata from an audio file represented as a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
347
+ This function is suitable for use in environments that support the ReadableStreamBYOBReader, which is **available in Node.js 20** and above.
348
+
349
+ ##### Syntax
350
+ ```ts
351
+ parseBlob(blob: Blob, options?: IOptions = {}): Promise<IAudioMetadata>
352
+ ```
353
+
354
+ ##### Parameters
355
+
356
+ - `blob`: [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
357
+
358
+ The Blob object containing the audio data to be parsed.
359
+ This can be a file or any binary data. If the Blob is an instance of File, its name will be used as the file path in the metadata.
360
+
361
+ - `options`: [IOptions](#ioptions-interface) (optional)
362
+
363
+ An optional configuration object that specifies parsing options.
364
+
365
+ ##### Returns
366
+
367
+ - `Promise<IAudioMetadata>`:
368
+
369
+ A promise that resolves to the metadata of the audio file.
370
+
371
+ ##### Example
372
+
373
+ ```js
374
+ import { parseBlob } from 'music-metadata';
375
+
376
+ (async () => {
377
+ const fileInput = document.querySelector('input[type="file"]');
378
+ const file = fileInput.files[0];
379
+
380
+ try {
381
+ const metadata = await parseBlob(file);
382
+ console.log(metadata);
383
+ } catch (error) {
384
+ console.error('Error parsing metadata:', error.message);
385
+ }
386
+ })();
387
+ ```
388
+
389
+ #### `parseBuffer` function
390
+
391
+ Parses metadata from an audio file where the audio data is held in a [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) or [Buffer](https://nodejs.org/api/buffer.html).
392
+ This function is particularly useful when you already have audio data in memory.
393
+
394
+ ##### Syntax
395
+ ```ts
396
+ parseBuffer(buffer: Uint8Array, fileInfo?: IFileInfo | string, opts?: IOptions = {}): Promise<IAudioMetadata>
397
+ ```
398
+
399
+ ##### Parameters
400
+ - `uint8Array`: [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
401
+
402
+ A [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) containing the audio data to be parsed.
403
+
404
+ - `fileInfo`: `IFileInfo` | `string` (optional)
405
+
406
+ An object containing file information such as mimeType and size.
407
+ Alternatively, you can pass a MIME-type string directly.
408
+ This helps the parser understand the format of the audio data.
409
+
410
+ - `options`: [IOptions](#ioptions-interface) (optional)
411
+
412
+ An optional configuration object that specifies parsing options.
413
+
414
+ ##### Returns
415
+ - `Promise<IAudioMetadata>`:
416
+
417
+ A promise that resolves to the metadata of the audio file.
418
+
419
+
420
+ ##### Example
421
+
422
+ ```js
423
+ import { parseBuffer } from 'music-metadata';
424
+ import fs from 'fs';
425
+
426
+ (async () => {
427
+ const buffer = fs.readFileSync('path/to/audio/file.mp3');
428
+
429
+ try {
430
+ const metadata = await parseBuffer(buffer, { mimeType: 'audio/mpeg' });
431
+ console.log(metadata);
432
+ } catch (error) {
433
+ console.error('Error parsing metadata:', error.message);
434
+ }
435
+ })();
436
+ ```
437
+
438
+ #### `parseFromTokenizer` function
439
+ Parses metadata from an audio source that implements the [strtok3](https://github.com/Borewit/strtok3) ITokenizer interface.
440
+ This is a low-level function that provides flexibility for advanced use cases,
441
+ such as parsing metadata from streaming audio or custom data sources.
442
+
443
+ This also enables special read modules like:
444
+ - [streaming-http-token-reader](https://github.com/Borewit/streaming-http-token-reader) for chunked HTTP(S) reading, using [HTTP range requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests).
445
+
446
+ ##### Syntax
447
+ ```ts
448
+ parseFromTokenizer(tokenizer: ITokenizer, options?: IOptions): Promise<IAudioMetadata>
449
+ ```
450
+
451
+ ##### Parameters
452
+ - `tokenizer: ITokenizer`
453
+
454
+ An instance of an ITokenizer that provides access to the audio data.
455
+ The tokenizer abstracts the reading process, enabling support for various types of sources, including streams, buffers, or custom data readers.
456
+
457
+ - `options`: [IOptions](#ioptions-interface) (optional)
458
+
459
+ An optional configuration object that specifies parsing options.
460
+
461
+ ##### Returns
462
+ - `Promise<IAudioMetadata>`:
463
+
464
+ A promise that resolves to the metadata of the audio source, including information like the title, artist, album, and more.
465
+
466
+
467
+ ##### Example
468
+ ````js
469
+ import { fromNodeProviderChain } from '@aws-sdk/credential-providers';
470
+ import { S3Client } from '@aws-sdk/client-s3';
471
+ import { makeTokenizer } from '@tokenizer/s3';
472
+ import { parseFromTokenizer as mmParseFromTokenizer } from 'music-metadata';
473
+
474
+ // Configure the S3 client
475
+ const s3 = new S3Client({
476
+ region: 'eu-west-2',
477
+ credentials: fromNodeProviderChain(),
478
+ });
479
+
480
+ // Helper function to create a tokenizer for S3 objects
481
+ async function makeS3TestDataTokenizer(key, options) {
482
+ return await makeTokenizer(s3, {
483
+ Bucket: 'music-metadata',
484
+ Key: key,
485
+ }, options);
486
+ }
487
+
488
+ // Function to read and log metadata from an S3 object
489
+ async function readMetadata() {
490
+ try {
491
+ // Create a tokenizer for the specified S3 object
492
+ const tokenizer = await makeS3TestDataTokenizer('path/to/audio/file.mp3', { disableChunked: false });
493
+
494
+ // Parse the metadata from the tokenizer
495
+ const metadata = await mmParseFromTokenizer(tokenizer);
496
+
497
+ // Log the retrieved metadata
498
+ console.log(metadata);
499
+ } catch (error) {
500
+ console.error('Error parsing metadata:', error.message);
501
+ }
502
+ }
503
+
504
+ // Execute the metadata reading function
505
+ readMetadata();
506
+ ````
507
+ ##### Additional Resources
508
+ - [strtok3](https://github.com/Borewit/strtok3) - Learn more about the `ITokenizer` interface and how to implement it for various use cases.
509
+ - [AWS SDK for JavaScript](https://aws.amazon.com/sdk-for-javascript/) - Documentation on using the AWS SDK to interact with S3 and other AWS services.
510
+ - [@tokenizer/s3](https://github.com/Borewit/tokenizer-s3) - Example of `ITokenizer` implementation.
511
+
512
+ ### Handling Parse Errors
513
+
514
+ `music-metadata` provides a robust and extensible error handling system with custom error classes that inherit from the standard JavaScript `Error`.
515
+ All possible parsing errors are part of a union type `UnionOfParseErrors`, ensuring that every error scenario is accounted for in your code.
516
+
517
+ #### Union of Parse Errors
518
+
519
+ All parsing errors extend from the base class `ParseError` and are included in the `UnionOfParseErrors` type:
520
+ ```ts
521
+ export type UnionOfParseErrors =
522
+ | CouldNotDetermineFileTypeError
523
+ | UnsupportedFileTypeError
524
+ | UnexpectedFileContentError
525
+ | FieldDecodingError
526
+ | InternalParserError;
527
+ ```
528
+
529
+ #### Error Types
530
+
531
+ - `CouldNotDetermineFileTypeError`: Raised when the file type cannot be determined.
532
+ - `UnsupportedFileTypeError`: Raised when an unsupported file type is encountered.
533
+ - `UnexpectedFileContentError`: Raised when the file content does not match the expected format.
534
+ - `FieldDecodingError`: Raised when a specific field in the file cannot be decoded.
535
+ - `InternalParserError`: Raised for internal parser errors.
536
+
537
+ ### Other functions
538
+
539
+ #### `orderTags` function
540
+
541
+ Utility to Converts the native tags to a dictionary index on the tag identifier
542
+
543
+ ```ts
544
+ orderTags(nativeTags: ITag[]): [tagId: string]: any[]
545
+ ```
546
+
547
+ ```js
548
+ import { parseFile, orderTags } from 'music-metadata';
549
+ import { inspect } from 'util';
550
+
551
+ (async () => {
552
+ try {
553
+ const metadata = await parseFile('../test/samples/MusicBrainz - Beth Hart - Sinner\'s Prayer [id3v2.3].V2.mp3');
554
+ const orderedTags = orderTags(metadata.native['ID3v2.3']);
555
+ console.log(inspect(orderedTags, { showHidden: false, depth: null }));
556
+ } catch (error) {
557
+ console.error(error.message);
558
+ }
559
+ })();
560
+ ```
561
+
562
+ #### `ratingToStars` function
563
+
564
+ 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.
565
+
566
+ ```ts
567
+ ratingToStars(rating: number): number
568
+ ```
569
+ #### `selectCover` function
570
+
571
+ Select cover image based on image type field, otherwise the first picture in file.
572
+
573
+ ```ts
574
+ export function selectCover(pictures?: IPicture[]): IPicture | null
575
+ ```
576
+
577
+ ```js
578
+ import { parseFile, selectCover } from 'music-metadata';
579
+
580
+ (async () => {
581
+ const {common} = await parseFile(filePath);
582
+ const cover = selectCover(common.picture); // pick the cover image
583
+ }
584
+ )();
585
+ ```
586
+
587
+ ### `IOptions` Interface
588
+ - `duration`: `boolean` (default: `false`)
589
+
590
+ If set to `true`, the parser will analyze the entire media file, if necessary, to determine its duration.
591
+ This option ensures accurate duration calculation but may increase processing time for large files.
592
+
593
+ - `observer`: `(update: MetadataEvent) => void;`:
594
+
595
+ A callback function that is invoked whenever there is an update to the common (generic) tag or format properties during parsing.
596
+ This allows for real-time updates on metadata changes.
597
+
598
+ - `skipCovers`: `boolean` (default: `false`)
599
+
600
+ If set to `true`, the parser will skip the extraction of embedded cover art (images) from the media file.
601
+ This can be useful to avoid processing unnecessary data if cover images are not required.
602
+
603
+ - `mkvUseIndex`: `boolean` (default: `false`)
604
+
605
+ If set to true, the parser will use the SeekHead element index to skip segment/cluster elements in Matroska-based files. This is an experimental feature and can significantly impact performance. It may also result in some metadata being skipped if it is not indexed.
606
+ If the SeekHead element is absent in the Matroska file, this flag has no effect.
607
+
608
+ > [!NOTE]
609
+ > - The `duration` option is typically included in most cases, but setting it to true ensures that the entire file is parsed if necessary to get an accurate duration.
610
+ > - Using `mkvUseIndex` can improve performance in Matroska files, but be aware of potential side effects, such as missing metadata due to skipped elements.
611
+
612
+
613
+ ### `IAudioMetadata` interface
614
+
615
+ If the returned promise resolves, the metadata (TypeScript `IAudioMetadata` interface) contains:
616
+ - [`metadata.format`](#metadataformat) Audio format information
617
+ - [`metadata.common`](#metadatacommon) Is a generic (abstract) way of reading metadata information.
618
+ - [`metadata.trackInfo`](#metadatatrackInfo) Is a generic (abstract) way of reading metadata information.
619
+ - `metadata.native` List of native (original) tags found in the parsed audio file.
620
+
621
+ #### `metadata.format`
622
+
623
+ The questionmark `?` indicates the property is optional.
624
+
625
+ Audio format information. Defined in the TypeScript `IFormat` interface:
626
+ - `format.container?: string` Audio encoding format. e.g.: 'flac'
627
+ - `format.codec?` Name of the codec (algorithm used for the audio compression)
628
+ - `format.codecProfile?: string` Codec profile / settings
629
+ - `format.tagTypes?: TagType[]` List of tagging formats found in parsed audio file
630
+ - `format.duration?: number` Duration in seconds
631
+ - `format.bitrate?: number` Number bits per second of encoded audio file
632
+ - `format.sampleRate?: number` Sampling rate in Samples per second (S/s)
633
+ - `format.bitsPerSample?: number` Audio bit depth
634
+ - `format.lossless?: boolean` True if lossless, false for lossy encoding
635
+ - `format.numberOfChannels?: number` Number of audio channels
636
+ - `format.creationTime?: Date` Track creation time
637
+ - `format.modificationTime?: Date` Track modification / tag update time
638
+ - `format.trackGain?: number` Track gain in dB
639
+ - `format.albumGain?: number` Album gain in dB
640
+
641
+ #### `metadata.trackInfo`
642
+
643
+ To support advanced containers like [Matroska](https://wikipedia.org/wiki/Matroska) or [MPEG-4](https://en.wikipedia.org/wiki/MPEG-4), which may contain multiple audio and video tracks, the **experimental**- `metadata.trackInfo` has been added,
644
+
645
+ `metadata.trackInfo` is either `undefined` or has an **array** of [trackInfo](#trackinfo)
646
+
647
+ ##### trackInfo
648
+
649
+ Audio format information. Defined in the TypeScript `IFormat` interface:
650
+ - `trackInfo.type?: TrackType` Track type
651
+ - `trackInfo.codecName?: string` Codec name
652
+ - `trackInfo.codecSettings?: string` Codec settings
653
+ - `trackInfo.flagEnabled?: boolean` Set if the track is usable, default: `true`
654
+ - `trackInfo.flagDefault?: boolean` Set if that track (audio, video or subs) SHOULD be active if no language found matches the user preference.
655
+ - `trackInfo.flagLacing?: boolean` Set if the track **may** contain blocks using lacing
656
+ - `trackInfo.name?: string` A human-readable track name.
657
+ - `trackInfo.language?: string` Specifies the language of the track
658
+ - `trackInfo.audio?: IAudioTrack`, see [`trackInfo.audioTrack`](#trackinfoaudiotrack)
659
+ - `trackInfo.video?: IVideoTrack`, see [`trackInfo.videoTrack`](#trackinfovideotrack)
660
+
661
+ ##### `trackInfo.audioTrack`
662
+
663
+ - `audioTrack.samplingFrequency?: number`
664
+ - `audioTrack.outputSamplingFrequency?: number`
665
+ - `audioTrack.channels?: number`
666
+ - `audioTrack.channelPositions?: Buffer`
667
+ - `audioTrack.bitDepth?: number`
668
+
669
+ ##### `trackInfo.videoTrack`
670
+
671
+ - `videoTrack.flagInterlaced?: boolean`
672
+ - `videoTrack.stereoMode?: number`
673
+ - `videoTrack.pixelWidth?: number`
674
+ - `videoTrack.pixelHeight?: number`
675
+ - `videoTrack.displayWidth?: number`
676
+ - `videoTrack.displayHeight?: number`
677
+ - `videoTrack.displayUnit?: number`
678
+ - `videoTrack.aspectRatioType?: number`
679
+ - `videoTrack.colourSpace?: Buffer`
680
+ - `videoTrack.gammaValue?: number`
681
+
682
+ #### `metadata.common`
683
+
684
+ [Common tag documentation](doc/common_metadata.md) is automatically generated.
685
+
686
+ ## Examples
687
+
688
+ 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.
689
+ ```js
690
+ import { parseStream } from 'music-metadata';
691
+ import { inspect } from 'util';
692
+
693
+ (async () => {
694
+ const metadata = await parseStream(someReadStream, {mimeType: 'audio/mpeg', size: 26838}, {duration: true});
695
+ console.log(inspect(metadata, {showHidden: false, depth: null}));
696
+ someReadStream.close();
697
+ }
698
+ )();
699
+ ```
700
+
701
+ ### Access cover art
702
+
703
+ Via `metadata.common.picture` you can access an array of cover art if present.
704
+ Each picture has this interface:
705
+
706
+ ```ts
707
+ /**
708
+ * Attached picture, typically used for cover art
709
+ */
710
+ export interface IPicture {
711
+ /**
712
+ * Image mime type
713
+ */
714
+ format: string;
715
+ /**
716
+ * Image data
717
+ */
718
+ data: Buffer;
719
+ /**
720
+ * Optional description
721
+ */
722
+ description?: string;
723
+ /**
724
+ * Picture type
725
+ */
726
+ type?: string;
727
+ }
728
+ ```
729
+
730
+ To assign `img` HTML-object you can do something like:
731
+ ```js
732
+ import {uint8ArrayToBase64} from 'uint8array-extras';
733
+
734
+ img.src = `data:${picture.format};base64,${uint8ArrayToBase64(picture.data)}`;
735
+ ```
736
+
737
+ ## Dependencies
738
+
739
+ Dependency diagram:
740
+ ```mermaid
741
+ graph TD;
742
+ MMN("music-metadata (Node.js entry point)")-->MMP
743
+ MMN-->FTN
744
+ MMP("music-metadata (primary entry point)")-->S(strtok3)
745
+ MMP-->TY(token-types)
746
+ MMP-->FTP
747
+ MMP-->UAE
748
+ FTN("file-type (Node.js entry point)")-->FTP
749
+ FTP("file-type (primary entry point)")-->S
750
+ S(strtok3)-->P(peek-readable)
751
+ S(strtok3)-->TO("@tokenizer/token")
752
+ TY(token-types)-->TO
753
+ TY-->IE("ieee754")
754
+ FTP-->TY
755
+ NS("node:stream")
756
+ FTN-->NS
757
+ FTP-->UAE(uint8array-extras)
758
+ style NS fill:#F88,stroke:#A44
759
+ style IE fill:#CCC,stroke:#888
760
+ style FTN fill:#FAA,stroke:#A44
761
+ style MMN fill:#FAA,stroke:#A44
762
+ ```
763
+
764
+ Dependency list:
765
+ - [tokenizer-token](https://github.com/Borewit/tokenizer-token)
766
+ - [strtok3](https://github.com/Borewit/strtok3)
767
+ - [token-types](https://github.com/Borewit/token-types)
768
+ - [file-type](https://github.com/sindresorhus/file-type)
769
+ - [@tokenizer-token](https://github.com/Borewit/tokenizer-token)
770
+ - [peek-readable](https://github.com/Borewit/peek-readable)
771
+
772
+ ## CommonJS backward compatibility
773
+
774
+ For legacy CommonJS projects needing to load the `music-metadata` ESM module, you can use the `loadMusicMetadata` function:
775
+ ```js
776
+ const { loadMusicMetadata } = require('music-metadata');
777
+
778
+ (async () => {
779
+ // Dynamically loads the ESM module in a CommonJS project
780
+ const mm = await loadMusicMetadata();
781
+
782
+ const metadata = await mm.parseFile('/path/to/your/file');
783
+ })();
784
+
785
+ ```
786
+
787
+ > [!NOTE]
788
+ > The `loadMusicMetadata` function is experimental.
789
+
790
+ ## Frequently Asked Questions
791
+
792
+ ### How can I traverse (a long) list of files?
793
+
794
+ What is important that file parsing should be done in a sequential manner.
795
+ 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.
796
+ There are multiple ways of achieving this:
797
+
798
+ 1. Using recursion
799
+
800
+ ```js
801
+ import { parseFile } from 'music-metadata';
802
+
803
+ function parseFiles(audioFiles) {
804
+
805
+ const audioFile = audioFiles.shift();
806
+
807
+ if (audioFile) {
808
+ return parseFile(audioFile).then(metadata => {
809
+ // Do great things with the metadata
810
+ return parseFiles(audioFiles); // process rest of the files AFTER we are finished
811
+ })
812
+ }
813
+ }
814
+
815
+ ```
816
+
817
+ 1. Use async/await
818
+
819
+ Use [async/await](https://javascript.info/async-await)
820
+
821
+ ```js
822
+ import { parseFile } from 'music-metadata';
823
+
824
+ // it is required to declare the function 'async' to allow the use of await
825
+ async function parseFiles(audioFiles) {
826
+
827
+ for (const audioFile of audioFiles) {
828
+
829
+ // await will ensure the metadata parsing is completed before we move on to the next file
830
+ const metadata = await parseFile(audioFile);
831
+ // Do great things with the metadata
832
+ }
833
+ }
834
+ ```
835
+
836
+ ## Licence
837
+
838
+ The MIT License (MIT)
839
+
840
+ Copyright © 2024 Borewit
841
+
842
+ 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:
843
+
844
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
845
+
846
+ 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.