'How to get the length of the sum of audio files using sox?

I have a script such as following

DIR=$1
ls $1 |sort -R |tail -$5 |while read file; do
    soxi -d $1$file
done

and it gives me an output like

00:40:35.18
00:43:41.23
01:04:19.64
00:59:41.92
00:51:16.32

As you can see, the program picks a random file (audio) from the folder and checks the time for each file. However, I need the sum of the length of all the audios.

How can I get the total number of audio files?



Solution 1:[1]

So here is an example, selecting 3 random "*.wav" files under some directory

#!/bin/bash
total=0
dir=/some/dir
while read -r f; do
    d=$(soxi -D "$f")
    echo "$d s. in $f"
    total=$(echo "$total + $d" | bc)
done < <(find "$dir" -iname "*.wav" | sort -R | head -3)

echo "Total : $total seconds"

If you can use Mediainfo instead of sox, you can get the durations in milliseconds, and use standard shell arithmetic for the additions. It also supports more audio formats.

#!/bin/bash
total=0
dir=/some/dir
while read -r f; do
    d=$(mediainfo --Output='General;%Duration%' "$f")
    ((total += d))
done < <(find "$dir" -iname "*.wav")

echo "Total : $total ms. or $((total/1000)) seconds"

(that 2nd example is without the random selection, for simplicity)

Solution 2:[2]

You can combine -D and -T for the total length in seconds, e.g.

soxi -DT *.wav

Source: https://stackoverflow.com/a/64826967/5090928

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 serg06