Last active
January 5, 2022 23:17
-
-
Save ggorlen/0a37a8e44004642e30d42148749b065e to your computer and use it in GitHub Desktop.
Convert files in a directory to mp3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Convert files in a directory to mp3 | |
| use strict; | |
| use warnings; | |
| use feature "say"; | |
| use Data::Dumper; | |
| use File::Basename; | |
| use File::Path; | |
| use File::Spec::Functions; | |
| sub convert_dir_to_mp3 { | |
| my $dir = shift @_; | |
| my $outdir = File::Spec::Functions::catfile($dir, shift @_); | |
| my $bitrate = shift @_; | |
| die "$outdir already exists" if -d $outdir; | |
| File::Path::make_path($outdir) or die "Failed to create path: $outdir"; | |
| opendir(DIR, $dir) or die "Could not open $dir\n"; | |
| while (my $file = readdir(DIR)) { | |
| next if !($file =~ /\.(?:wav|mp3|flac)$/i); | |
| $file = File::Spec::Functions::catfile($dir, basename($file)); | |
| my $outfile = File::Spec::Functions::catfile($outdir, basename($file)); | |
| $outfile =~ s/\.[^.]+$/\.mp3/g; | |
| # use -ac 1 for stereo to mono | |
| my $cmd = "ffmpeg -i \"$file\" -hide_banner -loglevel warning -vn ". | |
| "-write_id3v1 1 -id3v2_version 3 ". | |
| "-b:a ${bitrate}k \"$outfile\""; | |
| system($cmd) == 0 or die "$0: [$cmd] failed: $?\n"; | |
| } | |
| closedir(DIR); | |
| } | |
| if (!caller) { | |
| if (@ARGV) { | |
| for my $dir (@ARGV) { | |
| convert_dir_to_mp3($dir, "encoded", 128); | |
| } | |
| } | |
| else { | |
| while (<STDIN>) { | |
| chomp $_; | |
| if ($_ =~ /^(\d+)/ && $1 > 160) { | |
| $_ =~ s/\d+\t//g; | |
| convert_dir_to_mp3($_, "encoded", 128); | |
| } | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import re | |
| import sys | |
| from subprocess import run | |
| path = "." if len(sys.argv) < 2 else sys.argv[1] | |
| for root, dirs, files in os.walk(path): | |
| for f in files: | |
| f = os.path.join(path, root, f) | |
| if m := re.match(r"(.+)\.(?:m4a|mp4|wav|aiff|flac)$", f): | |
| print(f) | |
| outfile = m.group(1) + ".mp3" | |
| result = run([ | |
| "ffmpeg", | |
| "-n", # -n never overwrite (and exit), -y always overwrite | |
| "-hide_banner", | |
| "-loglevel", "warning", | |
| "-i", f, | |
| "-b:a", "192k", | |
| "-vn", | |
| outfile | |
| ]) | |
| if result.returncode != 0: | |
| print(f"error encoding `{f}`") | |
| sys.exit(1) | |
| os.remove(f) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment