#!/bin/bash # http://ffmpeg.org/download.html to get binary distribution for ogg codex
usage() { echo """ Usage: Script to compress audio resource for distribution!
-s <path to source dir> -d <path to dest dir> """ } #跳转到上一级目录 curpath=$(cd "$(dirname "$0")/"; pwd)
res_path="" des_path="" while getopts ":s::d:" opt do case $opt in s ) res_path=$OPTARG;; d ) des_path=$OPTARG;; ? ) echo "invalid param" exit 1;; esac done
if [[ ${#res_path} -eq 0 ]]; then #statements usage exit 1 fi
if [[ ${#des_path} -eq 0 ]]; then des_path="mp3" fi
if [[ ! -d ${des_path} ]];then mkdir ${des_path} else echo "clean directory ${des_path}.." rm ${des_path}/* echo "clean done!~" fi
// Define the ffmpeg command constCMD_MUSIC = path.join(__dirname, 'bin', 'ffmpeg');
// Function to compress audio files functioncompressAudioFiles(sourceDir, destDir = 'output', compressionThreshold = 1) { // Check if destination directory exists, if not create it if (destDir === 'output' && fs.existsSync(destDir)) { fs.rmdirSync(destDir, { recursive: true }); console.log(`Cleared directory: ${destDir}`); } if (!fs.existsSync(destDir)) { fs.mkdirSync(destDir, { recursive: true }); console.log(`Created directory: ${destDir}`); }
let totalMp3Files = 0; let filesMeetingCompressionCriteria = 0; let sizeReductionMetThreshold = 0; // Size reduction for files that meet the threshold let compressionResults = []; // Array to store results
// Function to process directory functionprocessDirectory(srcDir, destDir) { fs.readdirSync(srcDir).forEach(file => { const srcPath = path.join(srcDir, file); const relativePath = path.relative(sourceDir, srcPath); // Compute the relative path from the sourceDir const destPath = path.join(destDir, relativePath); // Append it to the destDir const destDirPath = path.dirname(destPath); // Directory of the destination file
if (fs.statSync(srcPath).isFile() && srcPath.toLowerCase().endsWith('.mp3')) { totalMp3Files++; const srcSize = fs.statSync(srcPath).size; let shouldDelete = false; // Flag to determine if the directory should be deleted
// Ensure destination directory exists before processing if (!fs.existsSync(destDirPath)) { fs.mkdirSync(destDirPath, { recursive: true }); }
if (audioMin(srcPath, destPath)) { const destSize = fs.statSync(destPath).size; const sizeDifference = (srcSize - destSize) / 1024; // Size difference in KB const srcSizeKB = (srcSize / 1024).toFixed(2); // Original size in KB const destSizeKB = (destSize / 1024).toFixed(2); // New size in KB
if (sizeDifference >= compressionThreshold) { filesMeetingCompressionCriteria++; sizeReductionMetThreshold += sizeDifference; compressionResults.push({ type: 'green', message: `File: ${relativePath}, Original: ${srcSizeKB} KB, New: ${destSizeKB} KB, Change: ${sizeDifference.toFixed(2)} KB` }); } elseif (sizeDifference > 0 && sizeDifference < compressionThreshold) { compressionResults.push({ type: 'blue', message: `File: ${relativePath}, Original: ${srcSizeKB} KB, New: ${destSizeKB} KB, Change: ${sizeDifference.toFixed(2)} KB but did not meet threshold` }); fs.unlinkSync(destPath); // Remove the file if it doesn't meet the compression threshold shouldDelete = true; } elseif (sizeDifference < 0) { compressionResults.push({ type: 'yellow', message: `File: ${relativePath}, Original: ${srcSizeKB} KB, New: ${destSizeKB} KB, Change: ${sizeDifference.toFixed(2)} KB` }); fs.unlinkSync(destPath); // Remove the file if it doesn't meet the compression threshold shouldDelete = true; } } else { shouldDelete = true; }
// Check and remove the directory if it was created but is empty if (shouldDelete && fs.existsSync(destDirPath) && fs.readdirSync(destDirPath).length === 0) { fs.rmdirSync(destDirPath); } } elseif (fs.statSync(srcPath).isDirectory()) { processDirectory(srcPath, destDir); } }); }
processDirectory(sourceDir, destDir);
const sizeReduction = sizeReductionMetThreshold / 1024; // Convert to MB for files that met the threshold console.log(`Total MP3 files in directory: ${totalMp3Files}`); console.log(`Total MP3 files meeting compression criteria (>= ${compressionThreshold}KB): ${filesMeetingCompressionCriteria}`); console.log(`Total size reduction after compression: ${sizeReduction.toFixed(2)} MB`);
// Main function functionmain() { const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question("请输入要压缩的包含音频文件的目录路径: ", (sourceDirectory) => { sourceDirectory = sourceDirectory.trim(); if (!sourceDirectory || !fs.existsSync(sourceDirectory)) { console.error('Error: Source directory is not specified or does not exist.'); rl.close(); process.exit(1); }
// Define the ffmpeg command constCMD_MUSIC = path.join(__dirname, 'bin', 'ffmpeg');
// Function to compress audio files functioncompressAudioFiles(sourceDir, destDir = 'output', compressionThreshold = 1) { // Check if destination directory exists, if not create it if (destDir === 'output' && fs.existsSync(destDir)) { fs.rmdirSync(destDir, { recursive: true }); console.log(`Cleared directory: ${destDir}`); } if (!fs.existsSync(destDir)) { fs.mkdirSync(destDir, { recursive: true }); console.log(`Created directory: ${destDir}`); }
let totalMp3Files = 0; let filesMeetingCompressionCriteria = 0; let sizeReductionMetThreshold = 0; // Size reduction for files that meet the threshold let compressionResults = []; // Array to store results
// Function to process directory functionprocessDirectory(srcDir, destDir) { fs.readdirSync(srcDir).forEach(file => { const srcPath = path.join(srcDir, file); const relativePath = path.relative(sourceDir, srcPath); // Compute the relative path from the sourceDir const destPath = path.join(destDir, relativePath); // Append it to the destDir const destDirPath = path.dirname(destPath); // Directory of the destination file
if (fs.statSync(srcPath).isFile() && srcPath.toLowerCase().endsWith('.mp3')) { totalMp3Files++; const srcSize = fs.statSync(srcPath).size; let shouldDelete = false; // Flag to determine if the directory should be deleted
// Ensure destination directory exists before processing if (!fs.existsSync(destDirPath)) { fs.mkdirSync(destDirPath, { recursive: true }); }
if (audioMin(srcPath, destPath)) { const destSize = fs.statSync(destPath).size; const sizeDifference = (srcSize - destSize) / 1024; // Size difference in KB const srcSizeKB = (srcSize / 1024).toFixed(2); // Original size in KB const destSizeKB = (destSize / 1024).toFixed(2); // New size in KB
if (sizeDifference >= compressionThreshold) { filesMeetingCompressionCriteria++; sizeReductionMetThreshold += sizeDifference; compressionResults.push({ type: 'green', message: `File: ${relativePath}, Original: ${srcSizeKB} KB, New: ${destSizeKB} KB, Change: ${sizeDifference.toFixed(2)} KB` }); } elseif (sizeDifference > 0 && sizeDifference < compressionThreshold) { compressionResults.push({ type: 'blue', message: `File: ${relativePath}, Original: ${srcSizeKB} KB, New: ${destSizeKB} KB, Change: ${sizeDifference.toFixed(2)} KB but did not meet threshold` }); fs.unlinkSync(destPath); // Remove the file if it doesn't meet the compression threshold shouldDelete = true; } elseif (sizeDifference < 0) { compressionResults.push({ type: 'yellow', message: `File: ${relativePath}, Original: ${srcSizeKB} KB, New: ${destSizeKB} KB, Change: ${sizeDifference.toFixed(2)} KB` }); fs.unlinkSync(destPath); // Remove the file if it doesn't meet the compression threshold shouldDelete = true; } } else { shouldDelete = true; }
// Check and remove the directory if it was created but is empty if (shouldDelete && fs.existsSync(destDirPath) && fs.readdirSync(destDirPath).length === 0) { fs.rmdirSync(destDirPath); } } elseif (fs.statSync(srcPath).isDirectory()) { processDirectory(srcPath, destDir); } }); }
processDirectory(sourceDir, destDir);
const sizeReduction = sizeReductionMetThreshold / 1024; // Convert to MB for files that met the threshold console.log(`Total MP3 files in directory: ${totalMp3Files}`); console.log(`Total MP3 files meeting compression criteria (>= ${compressionThreshold}KB): ${filesMeetingCompressionCriteria}`); console.log(`Total size reduction after compression: ${sizeReduction.toFixed(2)} MB`);
// Main function functionmain() { const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question("请输入要压缩的包含音频文件的目录路径: ", (sourceDirectory) => { sourceDirectory = sourceDirectory.trim(); if (!sourceDirectory || !fs.existsSync(sourceDirectory)) { console.error('Error: Source directory is not specified or does not exist.'); rl.close(); process.exit(1); }
let totalFilesCompared = 0; let totalFilesReplaced = 0; let totalFilesNotReplaced = 0; let originalTotalSize = 0; let replacedTotalSize = 0; let replacedFilesList = [];
// Function to replace original files with compressed ones functionreplaceOriginalFilesWithCompressed(srcDir, tgtDir, sizeDifferenceThreshold) { // Iterate over all files and directories in the current directory fs.readdirSync(srcDir).forEach(entry => { const sourceEntry = path.join(srcDir, entry); const targetEntry = path.join(tgtDir, entry);