#!/usr/bin/env -S deno run --allow-read /** * Basic TagLib-Wasm Usage Example * * This example demonstrates how to: * - Initialize TagLib-Wasm * - Load an audio file from disk * - Read audio properties and metadata * - Modify metadata tags * - Properly dispose of resources */ import { readFile } from "node:fs/promises"; import { TagLib } from "../../src/index.ts"; import { isMainModule } from "./is-main.ts"; async function demonstrateBasicUsage() { console.log("๐ŸŽต TagLib-Wasm - Basic Usage Example"); console.log("=".repeat(40)); try { // Step 1: Initialize TagLib-Wasm console.log("๐Ÿš€ Initializing TagLib-Wasm..."); const taglib = await TagLib.initialize(); console.log("โœ… TagLib initialized successfully\n"); // Step 2: Load an audio file const audioFilePath = "./tests/test-files/mp3/kiss-snippet.mp3"; console.log(`๐Ÿ“ Loading audio file: ${audioFilePath}`); // Open a buffer-mode handle, so Step 8's save() builds the modified file // in memory. A path-mode handle writes through to this fixture on save(). const bytes = await readFile(audioFilePath); const file = await taglib.open(new Uint8Array(bytes)); if (!file.isValid()) { throw new Error("Failed to load audio file"); } console.log("โœ… Audio file loaded successfully\n"); // Step 3: Read format information const format = file.getFormat(); console.log(`๐Ÿ“„ Detected format: ${format || "Unknown"}`); // Step 4: Read audio properties console.log("\n๐ŸŽง Audio Properties:"); const props = file.audioProperties(); if (!props) { throw new Error("No audio properties in this file"); } console.log(` Duration: ${props.duration} seconds`); console.log(` Bitrate: ${props.bitrate} kbps`); console.log(` Sample Rate: ${props.sampleRate} Hz`); console.log(` Channels: ${props.channels}`); // Step 5: Read existing metadata console.log("\n๐Ÿท๏ธ Current Tags:"); const currentTags = file.tag(); console.log(` Title: "${currentTags.title || "(empty)"}"`); console.log(` Artist: "${currentTags.artist || "(empty)"}"`); console.log(` Album: "${currentTags.album || "(empty)"}"`); console.log(` Year: ${currentTags.year || "(empty)"}`); console.log(` Track: ${currentTags.track || "(empty)"}`); console.log(` Genre: "${currentTags.genre || "(empty)"}"`); console.log(` Comment: "${currentTags.comment || "(empty)"}"`); // Step 6: Modify metadata console.log("\nโœ๏ธ Updating metadata..."); const tag = file.tag(); tag.setTitle("TagLib-Wasm Demo Song"); tag.setArtist("TagLib-Wasm"); tag.setAlbum("Demo Album"); tag.setYear(2025); tag.setTrack(1); tag.setGenre("Electronic"); tag.setComment("Generated by TagLib-Wasm example"); // Step 7: Read updated metadata console.log("\n๐Ÿท๏ธ Updated Tags:"); const updatedTags = file.tag(); console.log(` Title: "${updatedTags.title}"`); console.log(` Artist: "${updatedTags.artist}"`); console.log(` Album: "${updatedTags.album}"`); console.log(` Year: ${updatedTags.year}`); console.log(` Track: ${updatedTags.track}`); console.log(` Genre: "${updatedTags.genre}"`); console.log(` Comment: "${updatedTags.comment}"`); // Step 8: Save the edits into the in-memory copy console.log("\n๐Ÿ’พ Saving changes..."); const saveResult = file.save(); console.log(`๐Ÿ’พ Save result: ${saveResult ? "Success" : "Failed"}`); const modified = file.getFileBuffer(); console.log(`๐Ÿ“ฆ Modified file: ${modified.length} bytes (in memory)`); console.log( "โ„น๏ธ Nothing was written to disk: this handle was opened from a buffer. " + "To persist, use saveToFile(path) on a path-mode handle, or the " + "Simple API's applyTagsToFile().", ); // Step 9: Clean up resources console.log("\n๐Ÿงน Cleaning up..."); file.dispose(); console.log("โœ… Resources disposed successfully"); console.log("\n๐ŸŽ‰ Example completed successfully!"); } catch (error) { console.error("โŒ Error:", error instanceof Error ? error.message : error); if (error instanceof Error && error.stack) { console.error("Stack trace:", error.stack); } process.exitCode = 1; } } // Advanced example: Processing multiple files async function demonstrateBatchProcessing() { console.log("\n" + "=".repeat(40)); console.log("๐ŸŽต Batch Processing Example"); console.log("=".repeat(40)); try { const taglib = await TagLib.initialize(); const testFiles = [ "./tests/test-files/wav/kiss-snippet.wav", "./tests/test-files/mp3/kiss-snippet.mp3", "./tests/test-files/flac/kiss-snippet.flac", "./tests/test-files/ogg/kiss-snippet.ogg", "./tests/test-files/mp4/kiss-snippet.m4a", ]; console.log(`๐Ÿ“ Processing ${testFiles.length} files...\n`); for (const filePath of testFiles) { try { const file = await taglib.open(filePath); if (file.isValid()) { const props = file.audioProperties(); const tags = file.tag(); const format = file.getFormat(); console.log(`โœ… ${filePath}:`); console.log(` Format: ${format || "Unknown"}`); if (props) { console.log(` Duration: ${props.duration}s`); console.log(` Bitrate: ${props.bitrate} kbps`); } console.log(` Title: "${tags.title || "(none)"}"`); file.dispose(); } else { console.log(`โŒ ${filePath}: Invalid file`); } } catch (error) { console.log( `โŒ ${filePath}: ${error instanceof Error ? error.message : error}`, ); } console.log(); } console.log("๐ŸŽ‰ Batch processing completed!"); } catch (error) { console.error( "โŒ Batch processing error:", error instanceof Error ? error.message : error, ); } } // Run the examples if (isMainModule(import.meta)) { await demonstrateBasicUsage(); await demonstrateBatchProcessing(); }