- Play audio with Python
- 25 Answers 25
- How to Play Sound, Audio or MP3 Files in Python
- Playing Sound, Audio, or MP3 Files in Python on Windows
- Using Playsound
- Using VLC
- Using Pygame
- Playing Sound, Audio, or MP3 Files in Python on Linux
- Using Playsound
- Using os and mpg123
- Playing Sound, Audio, or MP3 Files in Python on macOS
- Using Afplay and os
- Conclusion
Play audio with Python
How can I play audio (it would be like a 1 second sound) from a Python script? It would be best if it was platform independent, but firstly it needs to work on a Mac. I know I could just execute the afplay file.mp3 command from within Python, but is it possible to do it in raw Python? I would also be better if it didn’t rely on external libraries.
Pyglet has the ability to play back audio through an external library called AVbin. Pyglet is a ctypes wrapper around native system calls on each platform it supports. Unfortunately, I don’t think anything in the standard library will play audio back.
If you need portable Python audio library try PyAudio. It certainly has a mac port. As for mp3 files: it’s certainly doable in «raw» Python, only I’m afraid you’d have to code everything yourself :). If you can afford some external library I’ve found some PyAudio — PyLame sample here.
try just_playback. It’s a wrapper around miniaudio that provides playback control functionality like pausing, resuming, seeking and setting the playback volume.
25 Answers 25
Your best bet is probably to use pygame/SDL. It’s an external library, but it has great support across platforms.
pygame.mixer.init() pygame.mixer.music.load("file.mp3") pygame.mixer.music.play()
You can find more specific documentation about the audio mixer support in the pygame.mixer.music documentation
For me, this was not working. I mean, it was playing but no sound. I added time.sleep(5) at the end and that worked. Python 3.6 on Windows 8.1
It doesn’t work on fedora with standard «.wav», «.mp3» and «.ogg» (Unable to open file ‘filename.format’)
@Calvin-Ruiz I just confirmed that I am able to use the above code in FC31 to play MP3 and Ogg files. I think you have a larger problem that likely needs some detailed knowledge of your platform.
Try playsound which is a Pure Python, cross platform, single function module with no dependencies for playing sounds.
Once you’ve installed, you can use it like this:
from playsound import playsound playsound('/path/to/a/sound/file/you/want/to/play.mp3')
Reading this made me so emotional. My eyes literally teared up with happiness. Did not expect that kind of reaction from myself. (They linked to a module I made.)
+1 for playsound . I just tested out a couple solutions here, and this one worked the easiest for me. Unfortunately the pygame solution didn’t work for me, during a brief test.
playsound is relying on a python 2 subprocess. Please use pip3 install PyObjC if you want playsound to run more efficiently.
Take a look at Simpleaudio, which is a relatively recent and lightweight library for this purpose:
import simpleaudio as sa wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav") play_obj = wave_obj.play() play_obj.wait_done()
Make sure to use uncompressed 16 bit PCM files.
You can find information about Python audio here: http://wiki.python.org/moin/Audio/
It doesn’t look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like PyMedia.
Sorry for the late reply, but I think this is a good place to advertise my library .
AFAIK, the standard library has only one module for playing audio: ossaudiodev. Sadly, this only works on Linux and FreeBSD.
UPDATE: There is also winsound, but obviously this is also platform-specific.
For something more platform-independent, you’ll need to use an external library.
My recommendation is the sounddevice module (but beware, I’m the author).
The package includes the pre-compiled PortAudio library for Mac OS X and Windows, and can be easily installed with:
pip install sounddevice --user
It can play back sound from NumPy arrays, but it can also use plain Python buffers (if NumPy is not available).
To play back a NumPy array, that’s all you need (assuming that the audio data has a sampling frequency of 44100 Hz):
import sounddevice as sd sd.play(myarray, 44100)
For more details, have a look at the documentation.
It cannot read/write sound files, you’ll need a separate library for that.
In pydub we’ve recently opted to use ffplay (via subprocess) from the ffmpeg suite of tools, which internally uses SDL.
It works for our purposes – mainly just making it easier to test the results of pydub code in interactive mode – but it has it’s downsides, like causing a new program to appear in the dock on mac.
I’ve linked the implementation above, but a simplified version follows:
import subprocess def play(audio_file_path): subprocess.call(["ffplay", "-nodisp", "-autoexit", audio_file_path])
The -nodisp flag stops ffplay from showing a new window, and the -autoexit flag causes ffplay to exit and return a status code when the audio file is done playing.
edit: pydub now uses pyaudio for playback when it’s installed and falls back to ffplay to avoid the downsides I mentioned. The link above shows that implementation as well.
Aaron’s answer appears to be about 10x more complicated than necessary. Just do this if you only need an answer that works on OS X:
from AppKit import NSSound sound = NSSound.alloc() sound.initWithContentsOfFile_byReference_('/path/to/file.wav', True) sound.play()
One thing. this returns immediately. So you might want to also do this, if you want the call to block until the sound finishes playing.
from time import sleep sleep(sound.duration())
Edit: I took this function and combined it with variants for Windows and Linux. The result is a pure python, cross platform module with no dependencies called playsound. I’ve uploaded it to pypi.
from playsound import playsound playsound('/path/to/file.wav', block = False)
MP3 files also work on OS X. WAV should work on all platforms. I don’t know what other combinations of platform/file format do or don’t work — I haven’t tried them yet.
@ErwinMayer — Are you talking about with the playsound module I wrote? I haven’t tested it on anything newer than Python 2.7.11. I can certainly look into fixing this on 3.5.
@ArtOfWarfare That’s simply not true. It is installed with the system python, but not with most distributions, including the official distributions from python.org. Most folks I know who use python install one of the distributions to get past the SIP restrictions. To get AppKit for most distributions, a user needs to pip install pyobjc. Which makes it most definitely a dependency.
s = Sound() s.read('sound.wav') s.play()
It is possible to play audio in OS X without any 3rd party libraries using an analogue of the following code. The raw audio data can be input with wave_wave.writeframes. This code extracts 4 seconds of audio from the input file.
import wave import io from AppKit import NSSound wave_output = io.BytesIO() wave_shell = wave.open(wave_output, mode="wb") file_path = 'SINE.WAV' input_audio = wave.open(file_path) input_audio_frames = input_audio.readframes(input_audio.getnframes()) wave_shell.setnchannels(input_audio.getnchannels()) wave_shell.setsampwidth(input_audio.getsampwidth()) wave_shell.setframerate(input_audio.getframerate()) seconds_multiplier = input_audio.getnchannels() * input_audio.getsampwidth() * input_audio.getframerate() wave_shell.writeframes(input_audio_frames[second_multiplier:second_multiplier*5]) wave_shell.close() wave_output.seek(0) wave_data = wave_output.read() audio_stream = NSSound.alloc() audio_stream.initWithData_(wave_data) audio_stream.play()
How to Play Sound, Audio or MP3 Files in Python
There are numerous ways for us to play sound, audio, or MP3 files using the Python programming language. These include modules such as playsound , VLC , pygame , mpg123 , etc. We can also play it natively on macOS and Linux as we will see later on.
Most of the modules that we will be using don’t come pre-installed with Python, which means we will have to install them ourselves. Therefore, you need to have Python and PIP installed on your system, before installing these Python modules.
Luckily, playing audio in Python is straightforward and can be done with a few lines of code. In this guide, we will be going over the steps to play sound, audio, or MP3 files in Python on Windows , Linux , and macOS .
Note: In this guide, a 4-second MP3 file is used named testaudio.mp3 and it is located in the same directory as the .py file which we will be using to run the code.
Table of Contents
Playing Sound, Audio, or MP3 Files in Python on Windows
Using Playsound
Playsound is a cross-platform Python module with no dependencies and a single function.
So, to use playsound to play audio:
If you would like to double-check that you’ve properly installed the module, enter python in the terminal to access the python terminal and then import playsound . If playsound is installed, there should be no errors in the output.
You can also enter pip list in the terminal to have a look at all the installed packages and their versions.
import playsound playsound.playsound('testaudio.mp3')
- After running the code, your audio will begin playing and will stop automatically depending on the length of your mp3 file.
Using VLC
VLC is an open-source and cross-platform media player that can be used to play audio and video files. VLC has a python module that enables us to play mp3 files.
Hence, to use VLC to play audio:
Confirm the installation by entering:
- We will be using another module alongside the Python VLC module in order to delay the execution of the file. The time module enables us to determine how long we want the file to delay execution so we can hear our audio being played. Otherwise, the file will finish executing immediately without our audio being played.
- In your code editor, enter the following:
import vlc import time p = vlc.MediaPlayer(‘testaudio.mp3’) p.play() print("The audio will finish playing in 4 seconds") time.sleep(4) p.stop()
The time.sleep(4) function tells the program to delay execution for 4 seconds before we call the p.stop() function. When running the program, it should look something like this:
A terminal window will appear and your audio should start playing. At the same time, the result of the print function is shown to indicate that the audio is 4 seconds long. The program will finish executing right after as that is the time we specify in time.sleep(4) .
Using Pygame
Pygame is a game development module that is cross-platform and enables us to use Python for graphics and audio purposes.
To use pygame to play audio:
import pygame import time pygame.mixer.init() # initialize mixer module pygame.mixer.music.load('testaudio.mp3') pygame.mixer.music.play() print("Audio will play for 4 seconds") time.sleep(4)
The result will look like this:
First, the audio will start playing, and the result of the print function will be shown on the screen. Then, the program will finish executing after 4 seconds as specified by the time.sleep() function.
Playing Sound, Audio, or MP3 Files in Python on Linux
Using Playsound
import playsound playsound.playsound(‘testaudio.mp3’)
Using os and mpg123
os is a standard Python module that doesn’t need to be installed. It allows us to interact with our Operating System through its functions. mpg123 is an open-source mp3 player for Linux systems.
So, we can use methods from both these functions to play audio files with Python through the following steps:
import os os.system(‘mpg123 ‘ + ‘testaudio.mp3’)
Playing Sound, Audio, or MP3 Files in Python on macOS
Using Afplay and os
To play audio on a macOS-based machine, we will be using afplay and os . Afplay is a tool that allows us to play audio from a file on macOS.
import os os.system(“afplay ” + “testaudio.mp3”)
Conclusion
Learning how to play audio, sounds, and MP3 files in Python can be quite useful in many circumstances. There are a number of reasons why someone may want to play music or audio in Python.
These include wanting to add to their programming skills, adding music to a game, adding sound effects to an app, and many more!
With that said, in this article, we looked at the steps to play sound , audio , or MP3 files in Python on Windows , Linux , and macOS machines . We hope you’ve found this guide helpful when it comes to playing audio in Python.
Feel free to share this post with your fellow coders to guide them through playing sound, audio, or MP3 files with Python on Windows, Linux, and macOS!