#283: Play Audio Files in Python
Before we can start with text-to-speech, we need to find a way to play an audio file with Python. In this post we play with two libraries to find something that works with a current version of Python.
Installation
Since Python does not have a built-in module to play audio files, we need to install third-party packages to get this functionality. Unfortunately, as with so many other topics, there are many great packages that are no longer maintained. Make sure that you check if the library you find gets updates before you use it in a new project.
For this post I focus on these two projects:
playsound3: Lightweight and simplepygame: Designed for games but useful for general audio playback
playsound3
We get two modes to play audio files with playsound3: blocking and non-blocking. If we use the straightforward way our script blocks until the audio file ends:
If we want to do something else while the audio plays, we can use the non-blocking option:
Both ways work without any problems and play our audio file.
pygame
Pygame is a library to create games in Python. We only care about the audio playing part, that only scratches the surface of the functionality. Since it is made to play games, we only get a non-blocking way to play the audio file:
Conclusion
Even when there is no module to play audio files directly in Python, we can find libraries that give us this functionality. Playsound3 is a good choice when we want a basic audio player, while pygame is great if we want to do more (like a game). For my current needs I go with playsound3.
With this building block we now have the groundwork ready so that we can start next week with turning text into audio.