Created
October 4, 2019 09:24
-
-
Save sota1235/40b33dc2c519940098adb0936a3c9759 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Usage: | |
// node index.js ${input} ${output} | |
// Require: | |
// Node.js | |
// ffmpeg | |
const fs = require('fs'); | |
const path = require('path'); | |
const exec = require('child_process').execSync; | |
const originDir = process.argv[2]; | |
const targetDir = process.argv[3]; | |
const walkDir = (dir, callback) => { | |
fs.readdirSync(dir).forEach( f => { | |
const dirPath = path.join(dir, f); | |
const isDirectory = fs.statSync(dirPath).isDirectory(); | |
isDirectory ? | |
walkDir(dirPath, callback) : callback(path.join(dir, f)); | |
}); | |
}; | |
const getCommand = (input, dist) => `ffmpeg "${dist}" -i "${input}" -codec:a libmp3lame -qscale:a 1`; | |
if (!originDir || !targetDir) { | |
console.error(` | |
invalid command argument | |
$ node index.js [input_dir] [output_dir] | |
`); | |
} | |
const inputFiles = []; | |
walkDir(originDir, (filePath) => { inputFiles.push(filePath); }); | |
const files = inputFiles.filter(file => /^.*\.(m4a)$/.test(file)) | |
console.log(`target file ${files.length}`); | |
for (let i=0;i<files.length;i++) { | |
const input = files[i]; | |
// ex) origin/artist/album_name/song.m4a => song | |
const inputFileName = path.basename(input, '.m4a'); | |
// ex) origin/artist/album_name/song.m4a => origin/artist/album_name | |
const inputDir = path.dirname(input); | |
// ex) origin/artist/album_name/song.m4a => artist/album_name | |
const dirForFile = path.join(...inputDir.split(path.sep).slice(1)); | |
// ex) origin/artist/album_name/song.m4a => target/artist/album_name | |
const distDir = path.join(targetDir, dirForFile); | |
// ex) origin/artist/album_name/song.m4a => target/artist/album_name/song.mp3 | |
const dist = path.join(distDir, `${inputFileName}.mp3`); | |
if (!fs.existsSync(distDir)) { | |
console.log(`mkdir ${distDir}`); | |
fs.mkdirSync(distDir, { recursive: true }); | |
} | |
if (!fs.existsSync(dist)) { | |
console.log(`in progress of converting ${input} to ${dist}`); | |
exec(getCommand(input, dist)); | |
} else { | |
console.log(`[SKIP] ${dist} already exists`); | |
} | |
} | |
console.log(`converted ${files.length} songs! Enjoy :)`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment