Skip to content

#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 simple
    pip install playsound3
    
  • pygame: Designed for games but useful for general audio playback
    pip install pygame
    

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:

1
2
3
4
from playsound3 import playsound

# Play sounds from disk
playsound("sample.mp3")

If we want to do something else while the audio plays, we can use the non-blocking option:

import time
from playsound3 import playsound

# You can play sounds in the background
sound = playsound("sample.mp3", block=False)

# and check if they are still playing
while sound.is_alive():
    print("Sound is still playing!")
    time.sleep(1)

# and stop them whenever you like.
sound.stop()

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:

1
2
3
4
5
6
7
8
9
import pygame

pygame.mixer.init()
pygame.mixer.music.load("sample.mp3")
pygame.mixer.music.play()

# Keep the program running while audio plays
while pygame.mixer.music.get_busy():
    continue

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.