Archive
Play a sound file from memory
Problem
I wanted to play short sound files a lot of times. Calling an external program each time to play a file would have been too slow. How to read sound files in the memory and play them from there?
Solution
First I tried the package simpleaudio. It worked well but it turned out that it couldn’t play every .wav file. VLC could play my file correctly, but simpleaudio just produced some noise. So I needed another solution.
And that’s how I found soundfile and sounddevice. Their usage is very simple:
import soundfile as sf
import sounddevice as sd
samples, samplerate = sf.read('file.wav')
sd.play(samples, samplerate)
sd.wait()
To use them, you also need to install numpy.
More info here: https://stackoverflow.com/a/42387773/232485
Update:
I had some .wav files that were not played correctly with soundfile+sounddevice. So I ended by using soundfile+sounddevice for certain files and by using simpleaudio for some other files.
Links
- Playing and Recording Sound in Python (this is where I read about
simpleaudio) - https://github.com/jabbalaci/keysound (my project, in which I needed to play sound files)
Play sound
In Python, for playing sound there are several options (see http://stackoverflow.com/search?q=python+play+sound). However, under Ubuntu I didn’t have much success with portable solutions :( I got most luck with wx.Sound('sound.wav') which used to work for a while but then it stopped… So I’ve decided to just call mplayer to do the job.
#!/usr/bin/env python import os SOUND = 'Gong.wav' command = 'mplayer %s 1>/dev/null 2>&1' % SOUND os.system(command)
Not too elegant but at least it works…
Notes
If you want to launch mplayer in the background without any verbosity, here is how to do that:
mplayer music.mp3 &>/dev/null </dev/null &
Update (20101016): I forgot to mention that with the help of mplayer, you can play videos too. Just pass an AVI instead of an MP3, for instance.
