Ever wanted to play music while you’re working in the command line? Maybe you want to play a podcast from the command line on Mac?
With the command line tool ‘afplay’ you can do just that, you can play practically any audio file format, whether it’s M4A, AAC, MP3, WAV, AIFF, or whatever else is on your Mac, and you can start the audio right from the Terminal.
How to Play Any Audio File from the Command Line
The afplay command is versatile and can play m4a, mp4, aac, aiff, wav, and many other audio file formats. To use it yourself, here is what you would want to do:
- Open the Terminal applicaiton found in /Applications/Utilities/
- Now type the following, using the path to the audio file you wish to play from the command line
- Audio begins playing immediate, to stop the audio from playing you can hit CONTROL + C at the command line
You can stop the audio any time with Control-C, otherwise the song will play itself through then terminate itself automatically when completed.
Don’t think of this as a terminal-based iTunes replacement (there’s a cool app called ViTunes for that though), because it’s not, it’s more of just a way to play a variety of audio files from the command line without having to enter into any GUI app. You won’t find any management utilities or syncing abilities within afplay.
That doesn’t mean you can’t run music in the background though.
How to Play Audio Files in the Background from Command Line
If you’d rather afplay run in the background while continuing to play the audio file, use this command:
afplay /path/to/audiofile.mp3 &
Note the ampersand is at the back of the command. This launches afplay into the background, if you want to shut it up you can just kill the afplay process with:
Or target the specific afplay process ID with kill -9:
Locate the PID for afplay as it’s running, then issue the command as follows:
kill -9 pid
That’ll end the process and music stream instantly.
Not that I’m condoning this type of behavior, but I recently used the afplay command to play a pretty amusing prank on a coworker by SSHing into his work machine and forcing him to listen to a Miley Cyrus song, he didn’t figure out what was going on until it was over and I told him. Yup, that’s our idea of fun here in nerdville.