Friday, February 19, 2010

sound.py




How to play a sound in Python

and my Linux only version with comments:


#!/usr/bin/python

from wave import open as waveOpen
from ossaudiodev import open as ossOpen
from ossaudiodev import AFMT_S16_NE

# Open the sound file
file='abacus_click.wav'
s = waveOpen(file,'rb')
(nc,sw,fr,nf,comptype, compname) = s.getparams( )

# Open the sound card
dsp = ossOpen('/dev/dsp','w')

# Setup the sound card
dsp.setparameters(AFMT_S16_NE, nc, fr)

# Read the sound file
data = s.readframes(nf)
s.close()

# Play the sound
dsp.write(data)

# Close the DSP device
dsp.close()