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

#!/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/');
Tags: #php
Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript, published a book on microservices, and is an organizer of Nodeschool SF.