Play sounds in the terminal with Python
I recently found a nice Python project called nava to play sounds in the terminal without using an audio player and I want to share it with you. 😁
I have also developed a small project around it since I like to write command-line interfaces. I will also present it to you.
Installation
To install nava, you will need Python 3.6 or higher.
$ pip install nava
# with poetry
$ poetry add nava
# with uv
$ uv pip install nava
If you don’t know poetry or uv, I have introduction articles on both of them.
Usage
The simplest usage is as follows:
import nava
nava.play("alarm.wav")
We just call the play
API of nava and pass it the path to a sound file. The sound file must have the WAV format for nava to work. Note also that on Mac, the MP3 format also works, but to avoid any issues it is best to only consider WAV files.
The previous code will block the main thread until the play ends. If we want to have the opportunity to do other stuff while playing the sound (like displaying a progress bar) we should call the API in async mode.
import time
from nava import play, stop
sound_id = play("alarm.wav", async_mode=True)
time.sleep(4) # do you custom stuff here
stop(sound_id)
When we play the file in async mode, we get a thread ID we can use to stop the play at any time.
We can also play the sound in a loop if we wish.
import time
from nava import play, stop
sound_id = play("alarm.wav", async_mode=True, loop=True)
time.sleep(100)
stop(sound_id)
When playing in a loop, the async mode set to True is mandatory.
This is all for this library, it is really easy to use. 😉
My project: a command line interface for nava
Surprisingly enough, I found that there is no command line added in nava (at the moment of writing this article) to play sounds, so I decided to write one since I like writing command line interfaces. 😁
The project is available on my GitHub. To run it you will need to have ffmepg on your machine and Python 3.11 or higher. You can use pipx to install it.
$ pipx install git+https://github.com/lewoudar/son
If you don’t know pipx, I have an introduction to it.
To play a sound is just as easy as:
$ son play alarm.wav
# to play in a loop
$ son play alarm.wav --loop
I have also integrated the Pomodoro activity. Here is a demo.
You can also manage playlists of songs.
By the way, if you need to extract audio from videos to compose your playlists, I have this little project that can come in handy. It comes from the following article.
This is all for this article, I hope you enjoy reading it. Take care of yourself and see you soon. 🙃