3

I am writing an audio playlist generator. However, I want it to output not only name and numeration in a strict row but also duration of an audio file. Is it any way I can do so without such hacks like:

print "#: $number\tDuration: ";
system("mp3info -p \"%m:%s\" \"$track\"");
print "\tNAME: $name";

If it is any important, my perl version is v5.16.3.

toolic
  • 57,801
  • 17
  • 75
  • 117
theoden8
  • 773
  • 7
  • 16
  • 1
    Have you taken a look at the MP3::Info module? https://metacpan.org/pod/MP3::Info – Trenton Trama May 13 '15 at 18:48
  • @TrentonTrama I'm afraid it works only for mp3, not for other audio formats. To be more precise, I need only mp3 and flac. – theoden8 May 13 '15 at 18:50
  • 1
    If you only need those two formats, you can use a combination of MP3::Info and Audio::FLAC::Decoder or Audio::FLAC::Header. Decoder has a `time_total` function that returns the total number of seconds. Header returns a hash that contains the time segments of the file. – Trenton Trama May 13 '15 at 18:54

1 Answers1

1

Ideally you want to determine the file type based on the file content instead of the extension, File::Type comes in handy for this. MP3::Info and Audio::Flac::Header are well written perl modules.

use File::Type;
use MP3::Info;
use Audio::FLAC::Header;

my $duration = -1;
my $ft = File::Type->new()->checktype_filename($track);

$duration = Audio::FLAC::Header
              ->new($track)
              ->tags()
              ->{trackTotalLengthSeconds} 
              if($ft eq 'audio/flac');

$duration = MP3::Info
              ->get_mp3info($track)
              ->{SECS} 
              if($ft eq 'audio/mpeg3');
harvey
  • 2,945
  • 9
  • 10
  • is it possible to use some universal method instead of including different modules with different methods? – theoden8 May 14 '15 at 22:24
  • You could use a library such as libavcodec - the engine behind ffmpeg. This knows about different files types, but the core engine is in c. [Video::FFmpeg](http://search.cpan.org/~randomman/Video-FFmpeg-0.47/lib/Video/FFmpeg.pm) may do what you want. – harvey May 14 '15 at 22:59
  • I will answer as soon as I overcome errors in installing FFmpeg modules. – theoden8 May 20 '15 at 18:04
  • 1
    In my case i used this answer: https://stackoverflow.com/questions/6239350/how-to-extract-duration-time-from-ffmpeg-output with `my $duration = \`ffmpeg -i \"$track\" 2>&1 | grep Duration | awk '{print \$2;}' | tr -d ,\`;` – theoden8 Jun 01 '15 at 20:02