Recursively convert OGGs to MP3s

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";

Tags: #php
Thomas Hunter II Avatar

Thomas is the author of Advanced Microservices and is 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.