public
Last active

Script for resampling a whole directory of music files recursively. Depends on ffmpeg (better build it with soxr)

  • Download Gist
gistfile1.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
<?php
 
/* config section { */
 
$input = "F:\\Music";
$output = "F:\\ResampledMusic";
 
// it will convert all the files to flacs
$ffmpegExecutable = "C:\\users\\nikita\\bin\\ffmpeg";
$ffmpegOptions = "-af aresample=resampler=soxr -ar 44100";
$inputAvailableExtensions = ["flac", "wav", "ape"];
$extensionToCopy = ["cue"];
 
/* config section } */
 
/* logic { */
 
$toConvert = [];
$toCopy = [];
foreach (getFlatFileTree($input) as $file) {
if (in_array(strtolower($file->getExtension()), $inputAvailableExtensions) && ! file_exists(getNewFilename($input, $output, $file))) {
$toConvert[] = $file;
} elseif (in_array(strtolower($file->getExtension()), $extensionToCopy) && ! file_exists(str_replace($input, $output, $file->getPathname()))) {
$toCopy[] = $file;
}
}
 
echo "There's ", count($toConvert), " files to convert and ", count($toCopy), " to copy...", "\r\n";
 
foreach ($toCopy as $from) {
$to = str_replace($input, $output, $from->getPathname());
$dir = dirname($to);
 
if ( ! file_exists($dir)) {
mkdir($dir, 0777, true);
}
 
copy($from->getPathname(), $to);
}
 
echo "All ", count($toCopy), " files were copied. Starting convertation:\r\n";
 
foreach ($toConvert as $from) {
$to = getNewFilename($input, $output, $from);
$dir = dirname($to);
 
if ( ! file_exists($dir)) {
mkdir($dir, 0777, true);
}
 
echo "\r\n\r\nConverting file ", $from->getPathname(), "\r\n\r\n";
exec($ffmpegExecutable . " -i \"" . $from->getPathname() . "\" " . $ffmpegOptions . " \"" . $to . "\"");
}
 
/* logic } */
 
function getFlatFileTree($dir)
{
$dir = new RecursiveDirectoryIterator($dir);
 
$files = [];
foreach ($dir as $file) {
if ($file->getFilename() === "." || $file->getFilename() === "..") {
continue;
}
 
if ($file->isDir()) {
$files = array_merge($files, getFlatFileTree($file->getPathname()));
} else {
$files[] = $file;
}
}
 
return $files;
}
 
function getNewFilename($input, $output, SplFileInfo $file)
{
global $inputAvailableExtensions;
 
$f = str_replace($input, $output, $file->getPathname());
$f = str_replace($inputAvailableExtensions, "flac", $f);
 
return $f;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.