Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play a Sound with Python [duplicate]

What's the easiest way to play a sound file (.wav) in Python? By easiest I mean both most platform independent and requiring the least dependencies. pygame is certainly an option, but it seems overkill for just sound.

like image 734
Claudiu Avatar asked Nov 20 '08 23:11

Claudiu


People also ask

Can you get Python to play a sound?

It is an easy task to play sound using Python script, because this language contains many modules to use script in order to to play or record sound. By using these modules, you can play audio files such as mp3, wav, and other audio file types.


1 Answers

For Windows, you can use winsound. It's built in

import winsound  winsound.PlaySound('sound.wav', winsound.SND_FILENAME) 

You should be able to use ossaudiodev for linux:

from wave import open as waveOpen from ossaudiodev import open as ossOpen s = waveOpen('tada.wav','rb') (nc,sw,fr,nf,comptype, compname) = s.getparams( ) dsp = ossOpen('/dev/dsp','w') try:   from ossaudiodev import AFMT_S16_NE except ImportError:   from sys import byteorder   if byteorder == "little":     AFMT_S16_NE = ossaudiodev.AFMT_S16_LE   else:     AFMT_S16_NE = ossaudiodev.AFMT_S16_BE dsp.setparameters(AFMT_S16_NE, nc, fr) data = s.readframes(nf) s.close() dsp.write(data) dsp.close() 

(Credit for ossaudiodev: Bill Dandreta http://mail.python.org/pipermail/python-list/2004-October/288905.html)

like image 191
orestis Avatar answered Sep 20 '22 14:09

orestis