Skip to content

Instantly share code, notes, and snippets.

@pavlobu
Created January 19, 2024 15:00
Show Gist options
  • Save pavlobu/c78888a577f16b3390be389119977e36 to your computer and use it in GitHub Desktop.
Save pavlobu/c78888a577f16b3390be389119977e36 to your computer and use it in GitHub Desktop.
Decode Cyrillic metadata in mp3 files fixing gibberish files description saved in windows 1251 encoding | using NodeJS
import mm from 'music-metadata';
import { promises as fs } from 'fs';
import path from 'path';
import iconv from 'iconv-lite';
import NodeID3 from 'node-id3';
// Function to convert from Windows-1251 to UTF-8
function convertFromWin1251(buffer) {
return iconv.decode(buffer, 'win1251');
}
// Recursive function to process all MP3 files in a directory
async function processDirectory(directory) {
const items = await fs.readdir(directory, { withFileTypes: true });
for (const item of items) {
const fullPath = path.join(directory, item.name);
if (item.isDirectory()) {
await processDirectory(fullPath); // Recurse into subdirectories
} else if (path.extname(fullPath).toLowerCase() === '.mp3') {
await processAndWriteMetadata(fullPath); // Process MP3 files
}
}
}
// Function to read, transliterate, and write metadata
async function processAndWriteMetadata(filePath) {
try {
const metadata = await mm.parseFile(filePath);
const tags = metadata.common;
// Convert and transliterate title and artist from Windows-1251 to UTF-8
if (tags.title) tags.title = convertFromWin1251(Buffer.from(tags.title, 'binary'));
if (tags.artist) tags.artist = convertFromWin1251(Buffer.from(tags.artist, 'binary'));
if (tags.album) tags.album = convertFromWin1251(Buffer.from(tags.album, 'binary'));
if (tags.copyright) tags.copyright = convertFromWin1251(Buffer.from(tags.copyright, 'binary'));
// Write the new metadata to the file
NodeID3.write(tags, filePath, function(err) {
if (err) console.error(`Error writing metadata to file ${filePath}: ${err}`);
else console.log(`Metadata successfully written to ${filePath}`);
});
} catch (error) {
console.error(`Error processing file ${filePath}: ${error.message}`);
}
}
// Start the processing with a given root directory
processDirectory('./path-to-folder-with-mp3-files');
{
"type": "module",
"dependencies": {
"iconv-lite": "^0.6.3",
"music-metadata": "^7.14.0",
"node-id3": "^0.2.6"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment