Play audio using Python

How can I play audio (it would be like a 1 second sound) from a Python script?

It would be better if it was platform independent, but firstly, it should work on a Mac.

I know that I can just execute the afplay file.mp3 from Python, but is it possible to do this in raw Python? I would also be better if he did not rely on external libraries.

+76
python audio
Nov 04 '08 at 3:11
source share
19 answers

Here you can find information about Python sound: http://wiki.python.org/moin/Audio/

It doesn't seem like it can play .mp3 files without external libraries. You can convert your .mp3 file to .wav or another format or use a library like PyMedia .

+14
Nov 04 '08 at 3:27
source share

It is best to use pygame / SDL . This is an external library, but it has great support on different platforms.

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

More detailed documentation on audio mixer support can be found in the pygame.mixer.music documentation

+28
Nov 04 '08 at 4:40
source share

Take a look at Simpleaudio , which is a relatively new and easy library for this purpose:

 > pip install simpleaudio 

Then:

 import simpleaudio as sa wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav") play_obj = wave_obj.play() play_obj.wait_done() 

Be sure to use uncompressed 16-bit PCM files.

+9
Mar 29 '16 at 12:17
source share

In pydub, we recently decided to use ffplay (via a subprocess) from the ffmpeg toolkit, which internally uses SDL.

It works for our purposes - it basically just simplifies testing the results of pydub code interactively, but it has drawbacks, for example, the appearance of a new program in the dock on Mac.

I linked the implementation above, but a simplified version:

 import subprocess def play(audio_file_path): subprocess.call(["ffplay", "-nodisp", "-autoexit", audio_file_path]) 

The -nodisp flag stops ffplay when a new window is -autoexit , and the -autoexit flag causes ffplay to exit and return a status code when playing an audio file.

edit : pydub now uses pyaudio to play when it is installed, and returns to ffplay to avoid the disadvantages mentioned below. The link above shows that implementation as well.

+8
Dec 23 '13 at 15:54
source share

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 . Unfortunately, this only works on Linux and FreeBSD.

UPDATE: there is also winsound , but obviously it also depends on the platform.

For something more platform independent, you will 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 using

 pip install sounddevice --user 

It can play sound from NumPy arrays, but it can also use simple Python buffers (if NumPy is not available).

To play a NumPy array, all you need (assuming the audio data has a sampling frequency of 44100 Hz):

 import sounddevice as sd sd.play(myarray, 44100) 

See the documentation for more details.

It cannot read / write sound files, for this you need a separate library.

+7
Dec 09 '15 at 12:37
source share

If you need a portable Python sound library, try PyAudio . It certainly has a mac port.

As for mp3 files: it is certainly possible in raw Python, but I'm afraid that you will have to code everything yourself :). If you can afford some kind of external library, I found here PyAudio - PyLame sample .

+6
Feb 03 '09 at 15:08
source share

Pyglet has the ability to play sound through an external library called AVbin . Pyglet is a wrapper of ctypes around its own system calls on each supported platform. Unfortunately, I do not think that sound will be played in the standard library.

+5
Nov 04 '08 at 14:37
source share

You can see this: http://www.speech.kth.se/snack/

 s = Sound() s.read('sound.wav') s.play() 
+4
Dec 24
source share

Also on OSX - from https://stackoverflow.com/a/464690/167328 using the OSX afplay command

 import subprocess subprocess.call(["afplay", "path/to/audio/file"]) 
+2
Jan 31 '15 at 5:45
source share

Aaron's answer seems about 10 times more complicated than necessary. Just do it 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 ... it returns immediately. Thus, you can also do this if you want the call to be blocked until the sound finishes playing.

 from time import sleep sleep(sound.duration()) 

Edit: I took this feature and combined it with the options for Windows and Linux. The result is pure python, a cross-platform module with no dependencies called playsound . I uploaded it to pypi.

 pip install playsound 

Then run it like this:

 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 do not know what other combinations of platform / file formats work or do not work - I have not tried them yet.

+2
Jan 25 '16 at 2:24
source share

You cannot do this without a custom library.

for Windows users who fall into this thread, try pythonwin . PyGame has some sound support. For hardware accelerated game sound, you may have to call OpenAL or similar using ctypes.

+1
Nov 04 '08 at 4:52
source share

VLC has some good python bindings, it worked better for me than pyglet, at least on Mac OS:

https://wiki.videolan.org/Python_bindings

But it relies on a VLC application, unfortunately

+1
May 9 '15 at
source share

You can play audio in OS X without any third-party libraries using an analogue of the following code. Raw audio can be entered 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() 
+1
Jan 02 '15 at 16:53 on
source share

Try PySoundCard , which uses PortAudio for playback available on many platforms. In addition, it recognizes "professional" sound devices with a large number of channels.

Here is a small example from the Readme:

 from pysoundcard import Stream """Loop back five seconds of audio data.""" fs = 44100 blocksize = 16 s = Stream(samplerate=fs, blocksize=blocksize) s.start() for n in range(int(fs*5/blocksize)): s.write(s.read(blocksize)) s.stop() 
+1
May 28 '16 at 17:30
source share

If you use OSX, you can use the os module or subprocess, etc., to invoke the OSX play command. From the OSX shell, it looks like

play "bah.wav"

It starts to play in about half a second on my machine.

0
Mar 27 '14 at 13:33
source share

You can just do it with cvlc- I did it like this:

 import os os.popen2("cvlc /home/maulo/selfProject/task.mp3 --play-and-exit") 

/home/maulo/selfProject/task.mp3. This is the location of my mp3 file. with "--play-and-exit" you can play sound without completing the vlc process.

0
Mar 20 '16 at 14:41
source share
Put this at the beginning of your python script that you write:
 import subprocess 
If the wav IS file is in the python script directory:
 f = './mySound.wav' subprocess.Popen(['aplay','-q',f) 
If the wav file is NOT in the python script directory:
 f = 'mySound.wav' subprocess.Popen(['aplay','-q', 'wav/' + f) 
If you want to know more about ip:
 man aplay 
0
Nov 11 '16 at 22:16
source share

This is the easiest and best 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.

0
Oct 05 '17 at 21:40
source share

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

Install via pip:

 $ pip install playsound 

After installation, you can use it as follows:

 from playsound import playsound playsound('/path/to/a/sound/file/you/want/to/play.mp3') 
0
Nov 27 '17 at 13:57
source share



All Articles