Search code examples
bashsummp3

Bash - calculate length of all mp3 files in one folder


I have the following command which returns the filenames and lengths of mp3s files:

mp3info -p "%f: %m:%02s\n" *.mp3

How can I use this in a bash script to return the total length (sum) of all mp3 files in a given directory? I would like to have the following notation: mm:ss


Solution

  • I'd go for a three step approach:

    1. instead of printing filename.mp3: mm:ss\n, omit the file name and print the overall seconds
    2. Build arithmetic expression from result, giving you total seconds
    3. divide by 60, round down to get minutes, calculate remainder of seconds.

    The first step is easy

    mp3info -o '%S' 
    

    will do the job. Now, we want things to give us a valid numerical expression of the form

    time1+time2+....

    so,

    mp3info -o '%S + '
    

    would seem wise.

    Then, because the last thing mp3info prints will then be a +, let's add a zero:

    "$(mp3info -o '%S + ') 0"
    

    and use that string in an arithmetic expression:

    total_seconds=$(( $(mp3info -o '%S + ' *.mp3) 0 ))
    

    Now, get the full minutes:

    full_minutes=$(( total_seconds / 60 ))
    

    and the remaining seconds

    seconds=$(( total_seconds % 60 ))
    

    So the total script would look like

    #!/bin/bash 
    # This code is under GPLv2
    # Author: Marcus Müller
    
    total_seconds=$(( $(mp3info -o '%S + ' *.mp3) 0 ))
    
    printf "%02d:%02d\n" $((total_seconds / 60)) $((total_seconds % 60))