Archive

Posts Tagged ‘sound’

Play a sound file from memory

February 6, 2024 Leave a comment

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

Categories: python Tags: , , ,

keysound

February 5, 2024 Leave a comment

Problem

I have a non-mechanical keyboard. However, when I press keys, I also want to hear some insane clickytty clicks. What to do?

Solution

If you don’t want to buy a new keyboard, you can try my keysound project. When you press a key, a short sound file is played.

At the bottom of the README of this project’s GitHub page, I also collected some related work, thus there are several alternatives available.

Categories: python Tags: , , ,

Play sound

September 26, 2010 1 comment

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.

Categories: python Tags: , , , , ,
Design a site like this with WordPress.com
Get started