Posted by & filed under PHP.

I recently had the need to change all of my OGG files to MP3s. Sure, there is a quality loss issue, but I prefer being able to play my music in my car and MP3 player over perfect quality.

This script will recursively find all OGG files, and convert them into an MP3 file with the same name but different extension. The file is placed in the same directory as the OGG. The original OGG file is then deleted. Essentially, it keeps your collection in the same location, it simply converts the OGGs to MP3s.

The script requires PHP as well as sox. You’ll want to update the last line of the file so that it points to the root of your music collection. Ideally, this script would accept CLI arguments for the root directory, as well as a flag for those who don’t want the original OGG file deleted, but I was lazy. :p

#!/usr/bin/php
<?php
function recurze($dir) {
	$iterator = new RecursiveIteratorIterator(
		new RecursiveDirectoryIterator($dir),
		RecursiveIteratorIterator::CHILD_FIRST
	);

	foreach ($iterator as $path) {
		if ($path->isFile()) {
			$filename = $path->__toString();
			$info = pathinfo($filename);
			if ($info['extension'] === 'ogg') {
				$new_filename = $info['dirname'] . '/' . $info['filename'] . '.mp3';
				echo "[  FOUND] $filename\n";
				echo "[CONVERT] $new_filename\n";
				system("sox \"$filename\" \"$new_filename\"", $status);
				if ($status === 0) {
					echo "[ DELETE] $filename\n";
					unlink($filename);
				} else {
					echo "[  ERROR] sox exit status $status\n";
					exit(1);
				}
			}
		}
	}
}

recurze('./Music/');

Thomas Hunter II

Support Thomas on Patreon. Thomas is the author of Advanced Microservices and a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.

Tags: