taglib-wasm
Version:
TagLib-Wasm is the universal tagging library for TypeScript/JavaScript platforms: Browsers, Node.js, Deno, Bun, Cloudflare Workers, and Electron apps
88 lines (87 loc) • 2.32 kB
JavaScript
import { FileOperationError, MetadataError } from "../errors.js";
import { mergeTagUpdates, readExtendedTag } from "../utils/tag-mapping.js";
import { getTagLib } from "./config.js";
import {
withAudioFile,
withAudioFileSave,
withAudioFileSaveToFile
} from "./with-audio-file.js";
async function readTags(file) {
return withAudioFile(file, (audioFile) => readExtendedTag(audioFile));
}
async function applyTags(file, tags) {
return withAudioFileSave(file, (audioFile) => {
mergeTagUpdates(audioFile, tags);
});
}
async function applyTagsToFile(file, tags) {
if (typeof file !== "string") {
throw new FileOperationError(
"save",
"applyTagsToFile requires a file path string to save changes"
);
}
await withAudioFileSaveToFile(file, (audioFile) => {
mergeTagUpdates(audioFile, tags);
});
}
async function readProperties(file) {
return withAudioFile(file, (audioFile) => {
const props = audioFile.audioProperties();
if (!props) {
throw new MetadataError(
"read",
"File may not contain valid audio data",
"audioProperties"
);
}
return props;
});
}
async function isValidAudioFile(file) {
try {
const taglib = await getTagLib();
const audioFile = await taglib.open(file);
try {
return audioFile.isValid();
} finally {
audioFile.dispose();
}
} catch {
return false;
}
}
async function readFormat(file) {
const taglib = await getTagLib();
const audioFile = await taglib.open(file);
try {
if (!audioFile.isValid()) {
return void 0;
}
return audioFile.getFormat();
} finally {
audioFile.dispose();
}
}
async function clearTags(file) {
return withAudioFileSave(file, (audioFile) => {
const cleared = {};
for (const key of Object.keys(audioFile.properties())) cleared[key] = [];
audioFile.setProperties(cleared);
audioFile.removePictures();
audioFile.setLyrics([]);
audioFile.setRatings([]);
if (audioFile.getChapters().length > 0) audioFile.setChapters([]);
if (audioFile.getBextData() !== void 0) audioFile.setBextData(null);
if (audioFile.getIxml() !== void 0) audioFile.setIxml(null);
});
}
export {
applyTags,
applyTagsToFile,
clearTags,
isValidAudioFile,
readFormat,
readProperties,
readTags
};