Play audio with Python

Viewed 266764

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.

26 Answers

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

Try playsound which is a Pure Python, cross platform, single function module with no dependencies for playing sounds.

Install via pip:

$ pip install playsound

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')

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.

This is the easiest & best iv'e found. It supports Linux/pulseaudio, Mac/coreaudio, and Windows/WASAPI.

import soundfile as sf
import soundcard as sc

default_speaker = sc.default_speaker()
samples, samplerate = sf.read('bell.wav')

default_speaker.play(samples, samplerate=samplerate)

See https://github.com/bastibe/PySoundFile and https://github.com/bastibe/SoundCard for tons of other super-useful features.

Install playsound package using :

pip install playsound

Usage:

from playsound import playsound
playsound("file location\audio.p3")

Mac OS I tried a lot of codes but just this works on me

import pygame
import time
pygame.mixer.init()
pygame.init()
pygame.mixer.music.load('fire alarm sound.mp3') *On my project folder*
i = 0
while i<10:
    pygame.mixer.music.play(loops=10, start=0.0)
    time.sleep(10)*to protect from closing*
    pygame.mixer.music.set_volume(10)
    i = i + 1

It's Simple. I did it this way.

For a wav file

from IPython.display import Audio
from scipy.io.wavfile import read

fs, data = read('StarWars60.wav', mmap=True)  # fs - sampling frequency
data = data.reshape(-1, 1)
Audio(data = data[:, 0], rate = fs)

For mp3 file

import IPython.display import Audio

Audio('audio_file_name.mp3')

Try sounddevice

If you don't have the module enter pip install sounddevice in your terminal.

Then in your preferred Python script (I use Juypter), enter

import sounddevice as sd

sd.play(audio, sr) will play what you want through Python

The best way to get the audio and samplerate you want is with the librosa module. Enter this in terminal if you don't have the librosa module.

pip install librosa

audio, sr = librosa.load('wave_file.wav')

Whatever wav file you want to play, just make sure it's in the same directory as your Python script. This should allow you to play your desired wav file through Python

Cheers, Charlie

P.S.

Once audio is a "librosa" data object, Python sees it as a numpy array. As an experiment, try playing a long (try 20,000 data points) thing of a random numpy array. Python should play it as white noise. The sounddevice module plays numpy arrays and lists as well.

In a Colab notebook you can do:

from IPython.display import Audio
Audio(waveform, Rate=16000)

This library aims to be simple, cross-platform and have many features: https://github.com/libwinmedia/libwinmedia-py

It requires a libwinmedia shared library, which you can download in Releases tab.

You can install it using pip install libwinmedia

Example:

import libwinmedia

player = libwinmedia.Player(True)

player.set_position_callback(lambda position: print(f"{position} ms."))
media = libwinmedia.Media("test.mp3")

player.open(media)

For those who use Linux and the other packages haven't worked on MP3 files, audioplayer worked fine for me:

https://pypi.org/project/audioplayer/

from audioplayer import AudioPlayer
AudioPlayer("path/to/somemusic.mp3").play(block=True)

This should work on Linux, Mac or Windows:

from preferredsoundplayer import *
soundplay("audio.wav")

Should work for mp3 also.

In Linux it will try up to 4 different methods. In Windows it uses winmm.dll. In Mac it uses afplay.

I wrote it because:

  • I kept having issues with cross-compatibility for playing sounds.
  • It also manually garbage collects calls to the winmm.dll player in Windows and appropriate closes finished sounds.
  • It has no dependencies, other than what comes with Windows 10, the standard Linux kernel, MacOS 10.5 or later, and the Python Standard Library.

You can install using pip install preferredsoundplayer (see project) or just utilize the source code which is a single file (source code) .

Related