This article explains how to play sound files in Python.

Python with it’s vast libraries has more than just one way of playing sound files. In this article we’ll be going through a few of the most popular of useful sound libraries that can be used to play sound, and in some cases, even record it too.

The list of libraries we will be covering:


Playsound

Easily the most simplest sound library, it consists of just one function used to play sound files.

First 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.

playsound('example_MP3.mp3')

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.


Pygame Mixer

First thing to know is that there is a difference between Music and Sound in the Pygame Mixer. Make sure to not confuse the two. Sound is mostly related to small side effects such as crash noises or beeps, generally anything just a few seconds long.

Music, on the other hand refers to longer tracks of audio, like background music or songs which can be up-to an hour long. It’s important to know this difference since there are separate libraries for Music and Sound.

Next, you should know about the types of files we’ll be using. The pygame mixer has the best support for wav files. It does support mp3, but not very reliably, so it’s best to stick to wav files for maximum compatibility.

Pygame Mixer – Music

We’ll cover music first as it’s the larger and more complex library.

pygame.mixer.music.load('background.wav')

First thing to do is load up the appropriate music file into the music.load() function. Remember to keep both in the same directory else you’ll have to mention the full file path.

Now comes the music.play() function, which is used to play the audio clip that has been loaded up. This function can be called in a variety of manners to change how it plays the audio clip.

pygame.mixer.music.play(0)
pygame.mixer.music.play(5)
pygame.mixer.music.play(-1)

Calling the music.play() with no parameters or 0 passed into it will only play the audio clip once. Passing -1 as the parameter will play the audio clip indefinitely.

Passing any other positive integer besides 0 will result in the song being repeated that many times. For instance, passing 5 will repeat the song 5 times. So the song played once, and repeated 5 times, playing a total of 6 times.

pygame.mixer.music.queue('next_audio.wav')

The Music library only allows one music file to be loaded and played at any given time. However, you are allowed to “queue” audio clips using the music.queue() function. Audio that has been queued will play right after the current music playing ends.

pygame.mixer.music.stop()

All things must come to end, and so too must music. The music.stop() function is used like the “stop” button on an audio player. Do not confuse this with pause. The stop function will end your current music playback and if you call the play() function again, it will start from the beginning.

pygame.mixer.music.pause()

Now obviously, you don’t always want to be using music.stop(). Sometimes you just want to pause so that you can pick up things later as you left them. Calling the music.pause() function will pause the music as it is.

pygame.mixer.music.unpause()

Calling the unpause() function will resume the music.

Pygame Mixer – Sound

Using simple sound files in Pygame is much simpler than playing music.

There are two steps involved in playing a sound. First you must create a sound object, as shown below.

sound_effect = pygame.mixer.Sound('crash.wav')

Next we call it with a simple play() method. An alternate option is to use the Sound.play() function, but that’s longer.

sound_effect.play()
#Alternate
pygame.mixer.Sound.play(sound_effect)

Unlike music, we can have multiple sound objects at any one point, though don’t try to play more than one at a time.


Playing audio with simpleaudio

import simpleaudio

filename = "background.wav"

sound_object = simpleaudio.WaveObject.from_wave_file(filename)
play_object = sound_object.play()
play_object.wait_done()

And that’s it. Pretty “simple” right? If you copy and run the above 5 lines of code, the audio you selected will begin to run. Now for the line by line explanation.

import simpleaudio

Imports the classes and functions inside the simpleaudio module for use in our program.

filename = "background.wav"

To keep things simple we’re going to place the file path of the sound file into a variable. Since the sound file is in the same location as our python script, we simply used it’s name, otherwise the full path would be required.

We typically use wav files with the audio libraries in Python. They are uncompressed “wave” sound files unlike something like mp3, which is compressed.

sound_object = simpleaudio.WaveObject.from_wave_file(filename)

You need to use the above function to create a “sound object” which we’ll be using later on. Remember to pass the filename variable, or just type in the filepath manually.

play_object = sound_object.play()

Creates a play-object and begins playing the sound file.

play_object.wait_done()

Using the play object we can modify the playing audio file a bit. Using the wait_done() method, we can have our program halt (while the audio is playing) until the audio track is completed.


Playing Audio with PyAudio

You’ve probably already noticed, but we’ll be needing more than just the pyaudio module. We’ll need some supporting modules such as wave. If you installed Pyaudio the way we instructed, these modules will install themselves automatically.

The code below is pretty self explanatory, especially with the help of the comments.

import pyaudio
import wave

filename = 'background.wav'

# Defines a chunk size of 1024 samples per data frame.
chunk = 1024  

# Open sound file  in read binary form.
file = wave.open(filename, 'rb')

# Initialize PyAudio
p = pyaudio.PyAudio()

# Creates a Stream to which the wav file is written to.
# Setting output to "True" makes the sound be "played" rather than recorded
stream = p.open(format = p.get_format_from_width(file.getsampwidth()),
                channels = file.getnchannels(),
                rate = file.getframerate(),
                output = True)

# Read data in chunks
data = file.readframes(chunk)

# Play the sound by writing the audio data to the stream
while data != '':
    stream.write(data)
    data = file.readframes(chunk)

# Stop, Close and terminate the stream
stream.stop_stream()
stream.close()
p.terminate()

To create a stream, you need to define certain things such as the number of channels, the sampling rate etc. Using commands like file.getnchannels() we extract the relevant data from the file and use it to create the appropriate audio stream.

The stop_stream() function isn’t actually needed here as by the time the code arrives at it’s location, the stream has already finished. It’s a useful function to know if you want to stop the stream half way through or something.

Our full article on PyAudio covers additional functions and explains how to record sound.


This marks the end of the playing sound files in Python article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article can be asked in the comments section below.

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Seowoong

Thanks! This helped me out sooo much!