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

function recurze($dir) {
	$iterator = new RecursiveIteratorIterator(
		new RecursiveDirectoryIterator($dir),

	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";
				} else {
					echo "[  ERROR] sox exit status $status\n";


Thomas Hunter II

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.
(Visited 127 times, 1 visits today)


  • Some Person

    Alternatively, MediaMonkey handles this with ease as long as you’re on Windows. I’ve heard it’ll run under Wine on Linux as well.

    • My GF loves that app. I must admit, it is a pretty good GUI tool, I’ve used it for mass-fixing of ID3 tags. It’ll run on OS X with Wine too.

  • Btw, I mentioned it to Tom already, but I thought it should be noted…

    One almost certainly doesn’t want to actually do this because it severely affects the sound quality. You get the worst of both codecs with no file size gain.

    But maybe many don’t care anyway… :/ Spose that’s why audiophools keep lossless on hand in the first place :D