This article covers the Python playsound library.
It’s fairly common to see the use of mp3 files in various kinds of software and games, ranging from simple 1 second sound effects to hour long sound tracks.
The Python playsound library offers you a easy and simple way to play sound files in Python. There are other libraries that can also be used such as Pygame, simpleaudio and winsound but playsound is by far the most simplest and easy to use, though it only offers a single feature, which is the simple playback of a sound file.
Before you proceed any further, make sure you download the playsound library from the command prompt using the
pip install playsound command.
We’ll be using a sample mp3 file for this exercise, which you can obtain using this download link.
Next up we’ll import the playsound function, from the playsound module using the following statement.
from playsound import playsound
To play the sound, we just need a single function, with a single line and a single parameter.
Call the playsound function, with the file path of the sound file passed into the parameter. Since our Python script and sound file were in the same location, we simply passed the sound file name.
And that’s it. Your sound file will begin to play and will end once it’s done playing. If you were hoping for something with more control the sound file playing, you can look up one of the other sound playing libraries in python.
If you receive a App-kit error, install the PyObjC library from the command prompt.
This marks the end of the Python playsound library. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article can be asked in the comments section below.