Skip to content

Instantly share code, notes, and snippets.

@nikita2206
Last active December 17, 2015 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikita2206/5661776 to your computer and use it in GitHub Desktop.
Save nikita2206/5661776 to your computer and use it in GitHub Desktop.
Script for resampling a whole directory of music files recursively. Depends on ffmpeg (better build it with soxr)
<?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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment