Skip to content

Instantly share code, notes, and snippets.

@ggorlen
Last active December 7, 2020 00:10
Show Gist options
  • Select an option

  • Save ggorlen/4f046d2f7ff62c18ec28b89b2ba09fde to your computer and use it in GitHub Desktop.

Select an option

Save ggorlen/4f046d2f7ff62c18ec28b89b2ba09fde to your computer and use it in GitHub Desktop.
Convert directory to mp3 recursively
# Convert files to mp3 recursively using ffmpeg, destroying originals
# FIXME fails on unicode chars
# FIXME should work on flac/wav rather than only high-bitrate mp3s
use strict;
use warnings;
use File::Copy;
use File::Find;
my $verbose = 0;
my $target_bitrate = 128;
# any mp3s above this bitrate will be converted to $target_bitrate
my $threshold_bitrate = 160;
sub process {
if (-f $_ && $_ =~ /\.mp3$/i) {
my $file = $_;
my $info = `ffmpeg -i \"$file\" 2>&1`;
$info =~ /^\s*Stream.+Audio: mp3.+?(\d+) kb\/s$/m;
return if $1 <= $threshold_bitrate;
print "$file\n" if $verbose;
my $cmd = "ffmpeg -i \"$file\" -hide_banner -loglevel warning -vn ".
"-write_id3v1 1 -id3v2_version 3 ".
"-b:a ${target_bitrate}k \"____$file\"";
system($cmd) == 0 or die "$0: [$cmd] failed: $?\n";
move("____$file", $file) or die "move failed: $!";
}
}
find(\&process, $ARGV[0] || ".");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment