[1] | 1 | #!/usr/bin/perl -w |
---|
| 2 | use strict; |
---|
| 3 | |
---|
| 4 | # extract one or more tracks from a FLAC file using its embedded cuesheet |
---|
| 5 | # save those tracks as wav or mp3 files |
---|
| 6 | # can also run them through a sox filter |
---|
| 7 | # TODO: separate sox filter for each track! |
---|
| 8 | |
---|
| 9 | use Getopt::Long; |
---|
[3] | 10 | use MusicBrainz; |
---|
[1] | 11 | |
---|
| 12 | GetOptions( |
---|
| 13 | 'D=s' => \my %TRACKS, |
---|
| 14 | 't=s' => \my $TYPE, |
---|
| 15 | 'x=s' => \my $SOX_FILTER, |
---|
| 16 | ); |
---|
| 17 | |
---|
| 18 | my $FLAC_FILE = shift or die "Need a flac file to decode"; |
---|
| 19 | |
---|
| 20 | # default to mp3 |
---|
| 21 | $TYPE ||= 'mp3'; |
---|
| 22 | |
---|
| 23 | # for getting track metadata from MusicBrainz |
---|
[3] | 24 | my $info; |
---|
[1] | 25 | if ($TYPE eq 'mp3') { |
---|
| 26 | require Audio::FLAC::Header; |
---|
| 27 | require LWP; |
---|
| 28 | require XML::XPath; |
---|
| 29 | require XML::XPath::XMLParser; |
---|
| 30 | |
---|
| 31 | my $flac = Audio::FLAC::Header->new($FLAC_FILE) or warn "Can't read FLAC header from $FLAC_FILE\n"; |
---|
| 32 | my $discid = $flac->tags('MBZ_DISCID') or warn "No MBZ_DISCID tag in $FLAC_FILE\n" if $flac; |
---|
| 33 | #TODO: calculate TOC and DISCID from cuesheet if there is no MBZ_DISCID tag present |
---|
| 34 | |
---|
[3] | 35 | $info = get_musicbrainz_info($discid); |
---|
[1] | 36 | } |
---|
| 37 | |
---|
| 38 | while (my ($tracknum, $title) = each %TRACKS) { |
---|
| 39 | if ($tracknum !~ /^\d+$/) { |
---|
| 40 | warn "Don't know what to do with track number '$tracknum'"; |
---|
| 41 | next; |
---|
| 42 | } |
---|
| 43 | my $start = $tracknum . '.1'; |
---|
| 44 | my $end = $tracknum + 1 . '.1'; |
---|
| 45 | my $cmd = qq{flac -d --cue $start-$end $FLAC_FILE -o - }; |
---|
| 46 | |
---|
| 47 | if ($SOX_FILTER) { |
---|
| 48 | $cmd .= qq{| sox -t wav - -t wav - $SOX_FILTER }; |
---|
| 49 | } |
---|
| 50 | |
---|
| 51 | $title = quotemeta($title); |
---|
| 52 | if ($TYPE eq 'mp3') { |
---|
| 53 | # bitrate of 192 |
---|
| 54 | $cmd .= qq{| lame -b 192}; |
---|
| 55 | # if there is track info, add it as ID3 tags |
---|
[3] | 56 | if ($info) { |
---|
| 57 | my $track = $info->{TRACKS}[$tracknum]; |
---|
[1] | 58 | $cmd .= sprintf q{ --tt %s --ta %s --tl %s --tn %d}, |
---|
[3] | 59 | quote($track->{TITLE}), |
---|
| 60 | quote($track->{ARTIST}), |
---|
| 61 | quote($info->{ALBUM}), |
---|
[1] | 62 | $tracknum; |
---|
| 63 | } |
---|
| 64 | $cmd .= qq{ - $title.mp3}; |
---|
| 65 | } elsif ($TYPE eq 'wav') { |
---|
| 66 | $cmd .= qq{> $title.wav}; |
---|
| 67 | } else { |
---|
| 68 | die "Unknown type: $TYPE\n"; |
---|
| 69 | } |
---|
| 70 | #die $cmd; |
---|
| 71 | system $cmd; |
---|
| 72 | |
---|
| 73 | print "\n" if $SOX_FILTER; |
---|
| 74 | } |
---|
| 75 | |
---|
| 76 | sub quote { |
---|
| 77 | my ($string) = @_; |
---|
| 78 | $string =~ s/"/\\"/g; |
---|
| 79 | return qq{"$string"}; |
---|
| 80 | } |
---|