Skip to content

Instantly share code, notes, and snippets.

@kreeger
Created February 18, 2012 18:50
Show Gist options
  • Save kreeger/1860644 to your computer and use it in GitHub Desktop.
Save kreeger/1860644 to your computer and use it in GitHub Desktop.
Ruby: Recursively convert to 128k MP3
#!/usr/bin/env ruby
# convert.rb
# Convert a directory (recursively!) full of audio files into 128k MP3.
# Good for burning folder-delimited MP3 CDs.
#
# Released under the license below (also at http://tomlea.co.uk/WTFBPPL.txt).
#
#
# DO WHAT THE FUCK YOU WANT TO + BEER/PIZZA PUBLIC LICENSE
# Version 1, May 2011
#
# Copyright (C) 2011 Tom Lea
#
#
# DO WHAT THE FUCK YOU WANT TO + BEER/PIZZA PUBLIC LICENSE
# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
# 0. You just DO WHAT THE FUCK YOU WANT TO.
# 1. If you make a substantial amount of money by exercising clause 0,
# you should consider buying the author a beer or a pizza.
def convert(source, destination)
`ffmpeg -i "#{source}" -ar 44100 -ab 128k "#{destination}" > /dev/null 2>&1`
end
def convert_dir(path)
# Get the full path.
path = File.expand_path(path)
puts "Searching for audio in \"#{File.basename path}.\""
# Reject any invalids, like DS_Store | .. | .
entries = Dir.entries(path).reject{|e| e =~ /^(\.{1,2})|(\.DS_Store)$/}
# Ensure all the files in our array are full-paths.
entries.collect!{|e|File.join(path, e)}
entries.each do |entry|
if File.directory?(entry)
# If this entry is a directory, call our function with it and iterate
# through its files.
convert_dir(entry)
else
# Otherwise, proceed if it's a valid music file type.
# Future: mime-type checking instead?
unless File.extname(entry) =~ /(mp3|aac|m4a)$/
puts "\"#{File.basename entry}\" not a valid audio file. Skipping."
next
end
source, destination = generate_names(entry)
puts "Converting #{source} to 128kbps MP3."
convert(source, destination)
File.delete(source)
end
end
end
def generate_names(filepath)
# Store the full path to our file, and create a destination name.
source = File.expand_path(filepath)
extension = File.extname(source)
source_base = source.chomp(extension)
destination = "#{source_base}.mp3"
# If there's going to be a naming conflict, handle it.
if destination == source
# Stick "old" in the filename.
new_source = [source_base, extension].join('.old')
File.rename(source, new_source)
source = new_source
end
return source, destination
end
convert_dir(ARGV[0] || Dir.pwd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment