How to play a sound from the macOS command line
By Flavio Copes
Learn how to play a sound from the macOS command line with the built-in afplay command, control the playback rate, and make your Mac talk with say.
Use the afplay built-in command:
afplay file.mp3
afplay ships with macOS, so there’s nothing to install. The name stands for Audio File Play, and it plays a sound file straight from the terminal. It’s handy when you want a script to beep when a long task finishes, or to play a notification without opening any app.
One thing to know: afplay blocks. It waits until the sound finishes before giving you the prompt back. That’s usually what you want at the end of a script. If you’d rather keep working, run it in the background by adding &:
afplay file.mp3 &
It handles the common formats out of the box, including MP3, WAV, AIFF, and m4a, since it uses the same Core Audio engine as the rest of the system.
Here are some more options from tldr.sh
afplay
Command-line audio player.
More information: https://ss64.com/osx/afplay.html.
- Play a sound file (waits until playback ends):
afplay path/to/file
- Play a sound file at 2x speed (playback rate):
afplay --rate 2 path/to/file
- Play a sound file at half speed:
afplay --rate 0.5 path/to/file
- Play the first N seconds of a sound file:
afplay --time seconds path/to/file
The --rate flag changes speed without you needing a separate audio editor. A rate above 1 speeds the sound up, and a rate below 1 slows it down. --time stops playback after the given number of seconds, which is nice for previewing the start of a long file.
Making your Mac talk
You can also make your Mac talk using the say command:
say "test"
say -v Fred "Isn't it nice to have a computer that will talk to you?"
say turns text into speech using the system voices. The -v flag picks a voice by name. Run say -v '?' to list every voice installed on your Mac, then pass one of those names.
I use say in scripts more than afplay, because I don’t need to keep a sound file around. A quick say "build done" at the end of a long command tells me it’s finished from across the room.