UNPKG

taglib-wasm

Version:

TagLib for TypeScript platforms: Deno, Node.js, Bun, Electron, browsers, and Cloudflare Workers

582 lines 19.5 kB
import type { TagLibModule, WasmModule } from "./wasm.ts"; import type { AudioProperties, FileType, OpenOptions, Picture, PropertyMap, Tag as BasicTag } from "./types.ts"; import { type TagLibWorkerPool } from "./worker-pool.ts"; import type { BatchOperation } from "./worker-pool.ts"; /** * Extended Tag interface with read/write capabilities for audio metadata. * Extends the basic Tag interface with setter methods for modifying metadata. * * @example * ```typescript * const file = await taglib.open("song.mp3"); * const tag = file.tag(); * * // Read metadata * console.log(tag.title); * * // Write metadata * tag.setTitle("New Title"); * tag.setArtist("New Artist"); * file.save(); * ``` */ export interface Tag extends BasicTag { /** Set the track title */ setTitle(value: string): void; /** Set the artist name */ setArtist(value: string): void; /** Set the album name */ setAlbum(value: string): void; /** Set the comment */ setComment(value: string): void; /** Set the genre */ setGenre(value: string): void; /** Set the release year */ setYear(value: number): void; /** Set the track number */ setTrack(value: number): void; } /** * Represents an audio file with metadata and audio properties. * Provides methods for reading and writing metadata, accessing audio properties, * and managing format-specific features. * * @example * ```typescript * const file = await taglib.open("song.mp3"); * * // Check if valid * if (!file.isValid()) { * throw new Error("Invalid audio file"); * } * * // Read metadata * const tag = file.tag(); * const props = file.audioProperties(); * * // Modify and save * tag.setTitle("New Title"); * file.save(); * * // Get modified buffer * const modifiedBuffer = file.getFileBuffer(); * * // Clean up * file.dispose(); * ``` */ export interface AudioFile { /** * Get the audio file format. * @returns The detected file type (e.g., "MP3", "FLAC", "MP4") */ getFormat(): FileType; /** * Get the tag object for reading/writing basic metadata. * @returns Tag object with getters and setters for metadata fields * @throws {Error} If unable to get tag from file */ tag(): Tag; /** * Get audio properties (duration, bitrate, sample rate, etc.). * @returns Audio properties or null if unavailable */ audioProperties(): AudioProperties | null; /** * Get all metadata properties as a key-value map. * Includes both standard and format-specific properties. * @returns PropertyMap with all available metadata */ properties(): PropertyMap; /** * Set multiple properties at once from a PropertyMap. * @param properties - Map of property names to values */ setProperties(properties: PropertyMap): void; /** * Get a single property value by key (typed version). * @param key - Property key from PROPERTIES constant * @returns Property value with correct type or undefined if not found */ getProperty<K extends import("./constants.ts").PropertyKey>(key: K): import("./constants.ts").PropertyValue<K> | undefined; /** * Get a single property value by key (string version for backward compatibility). * @param key - Property name (e.g., "ALBUMARTIST", "ACOUSTID_ID") * @returns Property value or undefined if not found */ getProperty(key: string): string | undefined; /** * Set a single property value (typed version). * @param key - Property key from PROPERTIES constant * @param value - Property value with correct type */ setProperty<K extends import("./constants.ts").PropertyKey>(key: K, value: import("./constants.ts").PropertyValue<K>): void; /** * Set a single property value (string version for backward compatibility). * @param key - Property name * @param value - Property value */ setProperty(key: string, value: string): void; /** * Check if this is an MP4/M4A file. * @returns true if the file is MP4/M4A format */ isMP4(): boolean; /** * Get an MP4-specific metadata item. * @param key - MP4 atom name (e.g., "----:com.apple.iTunes:iTunNORM") * @returns Item value or undefined if not found * @throws {Error} If not an MP4 file */ getMP4Item(key: string): string | undefined; /** * Set an MP4-specific metadata item. * @param key - MP4 atom name * @param value - Item value * @throws {Error} If not an MP4 file */ setMP4Item(key: string, value: string): void; /** * Remove an MP4-specific metadata item. * @param key - MP4 atom name to remove * @throws {Error} If not an MP4 file */ removeMP4Item(key: string): void; /** * Save all changes to the in-memory buffer. * Note: This does not write to disk, but updates the internal buffer. * Use getFileBuffer() to retrieve the modified data. * @returns true if save was successful */ save(): boolean; /** * Get the current file data as a buffer, including any modifications. * Call this after save() to get the updated file data. * @returns Uint8Array containing the complete file data */ getFileBuffer(): Uint8Array; /** * Save all changes to a file on disk. * This first saves changes to the in-memory buffer, then writes to the specified path. * @param path - Optional file path. If not provided, saves to the original path (if opened from a file). * @throws {Error} If no path is available or write fails */ saveToFile(path?: string): Promise<void>; /** * Check if the file was loaded successfully and is valid. * @returns true if the file is valid and can be processed */ isValid(): boolean; /** * Get all pictures/cover art from the audio file. * @returns Array of Picture objects */ getPictures(): Picture[]; /** * Set pictures/cover art in the audio file (replaces all existing). * @param pictures - Array of Picture objects to set */ setPictures(pictures: Picture[]): void; /** * Add a single picture to the audio file. * @param picture - Picture object to add */ addPicture(picture: Picture): void; /** * Remove all pictures from the audio file. */ removePictures(): void; /** * Release all resources associated with this file. * Always call this when done to prevent memory leaks. */ dispose(): void; /** * Get MusicBrainz Track ID. * @returns MusicBrainz Track ID or undefined if not set */ getMusicBrainzTrackId(): string | undefined; /** * Set MusicBrainz Track ID. * @param id - MusicBrainz Track ID (UUID format) */ setMusicBrainzTrackId(id: string): void; /** * Get MusicBrainz Release ID. * @returns MusicBrainz Release ID or undefined if not set */ getMusicBrainzReleaseId(): string | undefined; /** * Set MusicBrainz Release ID. * @param id - MusicBrainz Release ID (UUID format) */ setMusicBrainzReleaseId(id: string): void; /** * Get MusicBrainz Artist ID. * @returns MusicBrainz Artist ID or undefined if not set */ getMusicBrainzArtistId(): string | undefined; /** * Set MusicBrainz Artist ID. * @param id - MusicBrainz Artist ID (UUID format) */ setMusicBrainzArtistId(id: string): void; /** * Get AcoustID fingerprint. * @returns AcoustID fingerprint or undefined if not set */ getAcoustIdFingerprint(): string | undefined; /** * Set AcoustID fingerprint. * @param fingerprint - AcoustID fingerprint */ setAcoustIdFingerprint(fingerprint: string): void; /** * Get AcoustID ID. * @returns AcoustID ID or undefined if not set */ getAcoustIdId(): string | undefined; /** * Set AcoustID ID. * @param id - AcoustID ID */ setAcoustIdId(id: string): void; /** * Get ReplayGain track gain. * @returns ReplayGain track gain (e.g., "-6.54 dB") or undefined */ getReplayGainTrackGain(): string | undefined; /** * Set ReplayGain track gain. * @param gain - ReplayGain track gain (e.g., "-6.54 dB") */ setReplayGainTrackGain(gain: string): void; /** * Get ReplayGain track peak. * @returns ReplayGain track peak (0.0-1.0) or undefined */ getReplayGainTrackPeak(): string | undefined; /** * Set ReplayGain track peak. * @param peak - ReplayGain track peak (0.0-1.0) */ setReplayGainTrackPeak(peak: string): void; /** * Get ReplayGain album gain. * @returns ReplayGain album gain (e.g., "-7.89 dB") or undefined */ getReplayGainAlbumGain(): string | undefined; /** * Set ReplayGain album gain. * @param gain - ReplayGain album gain (e.g., "-7.89 dB") */ setReplayGainAlbumGain(gain: string): void; /** * Get ReplayGain album peak. * @returns ReplayGain album peak (0.0-1.0) or undefined */ getReplayGainAlbumPeak(): string | undefined; /** * Set ReplayGain album peak. * @param peak - ReplayGain album peak (0.0-1.0) */ setReplayGainAlbumPeak(peak: string): void; /** * Get Apple Sound Check normalization data. * @returns Apple Sound Check data (iTunNORM) or undefined */ getAppleSoundCheck(): string | undefined; /** * Set Apple Sound Check normalization data. * @param data - Apple Sound Check data (iTunNORM format) */ setAppleSoundCheck(data: string): void; } /** * Implementation of AudioFile interface using Embind API. * Wraps the native TagLib C++ FileHandle object. * * @internal This class is not meant to be instantiated directly. * Use TagLib.open() to create instances. */ export declare class AudioFileImpl implements AudioFile { private module; private fileHandle; private cachedTag; private cachedAudioProperties; private sourcePath?; private originalSource?; private isPartiallyLoaded; private partialLoadOptions?; constructor(module: TagLibModule, fileHandle: any, sourcePath?: string, originalSource?: string | File | ArrayBuffer | Uint8Array, isPartiallyLoaded?: boolean, partialLoadOptions?: OpenOptions); /** @inheritdoc */ getFormat(): FileType; /** @inheritdoc */ tag(): Tag; /** @inheritdoc */ audioProperties(): AudioProperties | null; /** @inheritdoc */ properties(): PropertyMap; /** @inheritdoc */ setProperties(properties: PropertyMap): void; /** @inheritdoc */ getProperty(key: string): string | undefined; /** @inheritdoc */ setProperty(key: string, value: string): void; /** @inheritdoc */ isMP4(): boolean; /** @inheritdoc */ getMP4Item(key: string): string | undefined; /** @inheritdoc */ setMP4Item(key: string, value: string): void; /** @inheritdoc */ removeMP4Item(key: string): void; /** @inheritdoc */ save(): boolean; /** @inheritdoc */ getFileBuffer(): Uint8Array; /** @inheritdoc */ saveToFile(path?: string): Promise<void>; /** @inheritdoc */ isValid(): boolean; /** @inheritdoc */ getPictures(): Picture[]; /** @inheritdoc */ setPictures(pictures: Picture[]): void; /** @inheritdoc */ addPicture(picture: Picture): void; /** @inheritdoc */ removePictures(): void; /** @inheritdoc */ dispose(): void; /** @inheritdoc */ getMusicBrainzTrackId(): string | undefined; /** @inheritdoc */ setMusicBrainzTrackId(id: string): void; /** @inheritdoc */ getMusicBrainzReleaseId(): string | undefined; /** @inheritdoc */ setMusicBrainzReleaseId(id: string): void; /** @inheritdoc */ getMusicBrainzArtistId(): string | undefined; /** @inheritdoc */ setMusicBrainzArtistId(id: string): void; /** @inheritdoc */ getAcoustIdFingerprint(): string | undefined; /** @inheritdoc */ setAcoustIdFingerprint(fingerprint: string): void; /** @inheritdoc */ getAcoustIdId(): string | undefined; /** @inheritdoc */ setAcoustIdId(id: string): void; /** @inheritdoc */ getReplayGainTrackGain(): string | undefined; /** @inheritdoc */ setReplayGainTrackGain(gain: string): void; /** @inheritdoc */ getReplayGainTrackPeak(): string | undefined; /** @inheritdoc */ setReplayGainTrackPeak(peak: string): void; /** @inheritdoc */ getReplayGainAlbumGain(): string | undefined; /** @inheritdoc */ setReplayGainAlbumGain(gain: string): void; /** @inheritdoc */ getReplayGainAlbumPeak(): string | undefined; /** @inheritdoc */ setReplayGainAlbumPeak(peak: string): void; /** @inheritdoc */ getAppleSoundCheck(): string | undefined; /** @inheritdoc */ setAppleSoundCheck(data: string): void; } /** * Main TagLib interface for audio metadata operations. * Provides methods to open audio files and access TagLib functionality. * * @example * ```typescript * // Option 1: Auto-initialize * const taglib = await TagLib.initialize(); * * // Option 2: Manual initialization * import { loadTagLibModule } from "taglib-wasm"; * const module = await loadTagLibModule(); * const taglib = new TagLib(module); * * // Open and process a file * const file = await taglib.open("song.mp3"); * const tag = file.tag(); * console.log(`Title: ${tag.title}`); * file.dispose(); * ``` */ export declare class TagLib { private module; private workerPool?; constructor(module: WasmModule); /** * Initialize TagLib with optional configuration. * This is the recommended way to create a TagLib instance. * * @param options - Optional configuration for loading the WASM module * @returns Promise resolving to initialized TagLib instance * * @example * ```typescript * // Basic usage * const taglib = await TagLib.initialize(); * * // With pre-loaded WASM binary (for offline usage) * const wasmBinary = await fetch("taglib.wasm").then(r => r.arrayBuffer()); * const taglib = await TagLib.initialize({ wasmBinary }); * * // With custom WASM URL * const taglib = await TagLib.initialize({ wasmUrl: "/assets/taglib.wasm" }); * * // With worker pool enabled * const taglib = await TagLib.initialize({ useWorkerPool: true }); * ``` */ static initialize(options?: { wasmBinary?: ArrayBuffer | Uint8Array; wasmUrl?: string; useWorkerPool?: boolean; workerPoolOptions?: { size?: number; debug?: boolean; }; }): Promise<TagLib>; /** * Enable or disable worker pool for this TagLib instance */ setWorkerPool(pool: TagLibWorkerPool | null): void; /** * Get the current worker pool instance */ getWorkerPool(): TagLibWorkerPool | undefined; /** * Open an audio file from various sources. * Automatically detects the file format based on content. * * @param input - File path (string), ArrayBuffer, Uint8Array, or File object * @returns Promise resolving to AudioFile instance * @throws {Error} If the file format is invalid or unsupported * @throws {Error} If the module is not properly initialized * * @example * ```typescript * // From file path * const file = await taglib.open("song.mp3"); * * // From ArrayBuffer * const file = await taglib.open(arrayBuffer); * * // From Uint8Array * const file = await taglib.open(uint8Array); * * // From File object (browser) * const file = await taglib.open(fileObject); * * // Remember to dispose when done * file.dispose(); * ``` */ open(input: string | ArrayBuffer | Uint8Array | File, options?: OpenOptions): Promise<AudioFile>; /** * Update tags in a file and save changes to disk in one operation. * This is a convenience method that opens, modifies, saves, and closes the file. * * @param path - File path to update * @param tags - Object containing tags to update * @throws {Error} If file operations fail * * @example * ```typescript * await taglib.updateFile("song.mp3", { * title: "New Title", * artist: "New Artist" * }); * ``` */ updateFile(path: string, tags: Partial<BasicTag>): Promise<void>; /** * Copy a file with new tags. * Opens the source file, applies new tags, and saves to a new location. * * @param sourcePath - Source file path * @param destPath - Destination file path * @param tags - Object containing tags to apply * @throws {Error} If file operations fail * * @example * ```typescript * await taglib.copyWithTags("original.mp3", "copy.mp3", { * title: "Copy of Song", * comment: "This is a copy" * }); * ``` */ copyWithTags(sourcePath: string, destPath: string, tags: Partial<BasicTag>): Promise<void>; /** * Execute batch operations on a file using the worker pool. * This method provides efficient batch processing using Web Workers. * * @param file - File path or Uint8Array * @param operations - Array of operations to execute * @returns Result of the batch operations * * @example * ```typescript * const result = await taglib.batchOperations("song.mp3", [ * { method: "setTitle", args: ["New Title"] }, * { method: "setArtist", args: ["New Artist"] }, * { method: "save" } * ]); * ``` */ batchOperations(file: string | Uint8Array, operations: BatchOperation[]): Promise<any>; /** * Process multiple files in parallel using the worker pool. * * @param files - Array of file paths * @param operation - Operation to perform on each file * @returns Array of results * * @example * ```typescript * const tags = await taglib.processFiles( * ["song1.mp3", "song2.mp3", "song3.mp3"], * "readTags" * ); * ``` */ processFiles<T>(files: string[], operation: "readTags" | "readProperties"): Promise<T[]>; /** * Get the TagLib version. * @returns Version string (e.g., "2.1.0") */ version(): string; } /** * Create a TagLib instance from a pre-loaded Wasm module. * For advanced users who need custom module configuration. * * @param module - Pre-loaded Wasm module from loadTagLibModule() * @returns Promise resolving to TagLib instance * * @example * ```typescript * import { loadTagLibModule, createTagLib } from "taglib-wasm"; * * const module = await loadTagLibModule(); * const taglib = await createTagLib(module); * ``` */ export declare function createTagLib(module: WasmModule): Promise<TagLib>; /** * Re-export error types for convenient error handling */ export { EnvironmentError, FileOperationError, InvalidFormatError, isEnvironmentError, isFileOperationError, isInvalidFormatError, isMemoryError, isMetadataError, isTagLibError, isUnsupportedFormatError, MemoryError, MetadataError, SUPPORTED_FORMATS, TagLibError, TagLibInitializationError, UnsupportedFormatError, } from "./errors.ts"; export type { TagLibErrorCode } from "./errors.ts"; //# sourceMappingURL=taglib.d.ts.map