![]() |
VOOZH | about |
In this article, we will explore how to play sound in Python using some of the most popular audio libraries. Whether you need to play a simple sound effect or work with complex audio files, these methods will cover your needs.
We'll discuss five different approaches to play sound in Python, using modules like playsound, pydub, tksnack, and more. You'll also find examples to make implementation easier.
Playing sound in Python is a useful feature in various applications, from games and user notifications to more complex audio-processing projects. Depending on the format (WAV, MP3, etc.) and the functionality required, you can select the most suitable library for your project. Let’s dive into the different methods.
Run the following command to install the packages:
pip install playsoundExample: For WAV format
Output:
Example: For mp3 format
Output:
Run the following commands to install the packages:
sudo apt-get install ffmpeg libavcodec-extra
pip install pydubNote: You can open WAV files with python. For opening mp3, you'll need ffmpeg or libav.
This module uses the from_wav() method for playing wav file and from_mp3() method for playing an mp3 file. The play() method is used to play the wav and mp3 file:
Example 1: For WAV format
Output:
Example 2: For mp3 format
Output:
The tksnack module depends upon a module named tkinter to activate a tk object in the python script. You must install tkinter and tksnack packages for Python. Run the following commands to install the packages:
sudo apt-get install python3-tk
sudo apt-get install python3-tksnackThe play() method is used to play the audio files. The blocking argument states that the sound will play asynchronously.
Example:
Output:
In this method, we play sounds natively on our system. This method plays the audio file with an external player installed on your terminal.
Example 1: For Mac OS X
Output:
Example 2: For Linux
Output:
This is mainly designed to play WAV files and NumPy arrays. Run the following command to install the packages:
$ sudo apt-get install libasound2-dev
$ pip3 install simpleaudioThe play() method is used to play the audio files.
Example:
Output:
In this guide, we covered multiple ways to play sound in Python using various libraries like playsound, pydub, tksnack, simpleaudio, and native players. Each method has its strengths and weaknesses, so the best option depends on your specific use case.
For basic sound playback, playsound is quick and simple. If you need more advanced functionality, such as audio processing, consider using pydub. For GUI-based applications, tksnack could be a good fit. And if you're looking for low-latency WAV playback, simpleaudio is the way to go.
Whether you're building a game, a notification system, or a more complex audio processing tool, these libraries will help you get sound playing in Python with ease