AFPlay with progress bar - play music from terminal in mac

AFPlay is nice utility used to play audio files from terminal in Mac OS. The following script extends the utility by adding a cool progress bar to it. The script relies on a bunch of commands to work: afplay obviously, afinfo for getting runtime, bc for command line math processing, yes, head and tput commands.


~/bin/afplay2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/bin/zsh

function progress() {
FILL_CHAR="▮"
EMPTY_CHAR="▯"

MAXCHAR=80
progress=$1

filled=`echo "scale=0; $progress / 1.25" | bc`
empty=`echo "scale=0; $MAXCHAR - $filled" | bc`

if [[ $filled -gt 0 ]]; then
echo -ne `yes $FILL_CHAR | head -n$filled | tr -d '\n'`
fi

if [[ $empty -gt 0 ]]; then
echo -ne `yes $EMPTY_CHAR | head -n$empty | tr -d '\n'`
fi

echo -ne '\r'
}

# trap ctrl-c and call ctrl_c()
trap ctrl_c INT
trap ctrl_c EXIT

function ctrl_c() {
# stop playing all files
killall afplay > /dev/null 2>&1

# make cursor normal
tput cnorm
exit 0
}


f="$1"

if [ ! -f $f ]; then
afplay "$f"
exit
fi

# get file duration
duration=`afinfo "$f" | grep "estimated duration" | awk '{ print $3 }' | bc`

# play the file in background and disown the process
afplay "$f" &!

# hide the blinking cursor
tput civis

# update progress every second
for t in $(seq 1 $duration); do
progress=`echo "scale=0; $t * 100 / $duration" | bc`
echo -ne `progress $progress`
sleep 1
done

Alias “play” to the script, and voila!

play