audio - how to play wav file in python? -


i tried pygame playing wav file this:

import pygame pygame.init()  pygame.mixer.music.load("mysound.wav") pygame.mixer.music.play() pygame.event.wait() 

but change voice , don't know why! read this link solutions , can't solve problem playing wave file!

for solution dont know should import?

s = sound()  s.read('sound.wav')  s.play() 

and solution /dev/dsp dosen't exist in new version of linux :

from wave import open waveopen ossaudiodev import open ossopen s = waveopen('tada.wav','rb') (nc,sw,fr,nf,comptype, compname) = s.getparams( ) dsp = ossopen('/dev/dsp','w') try:   ossaudiodev import afmt_s16_ne except importerror:   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() 

and when tried pyglet give me error:

import pyglet  music = pyglet.resource.media('mysound.wav') music.play()  pyglet.app.run() --------------------------  nima@ca005 desktop]$ python play.py traceback (most recent call last):   file "play.py", line 4, in <module>     music = pyglet.resource.media('mysound.wav')   file "/usr/lib/python2.7/site-packages/pyglet/resource.py", line 587, in media     return media.load(path, streaming=streaming)   file "/usr/lib/python2.7/site-packages/pyglet/media/__init__.py", line 1386, in load     source = _source_class(filename, file)   file "/usr/lib/python2.7/site-packages/pyglet/media/riff.py", line 194, in __init__     format = wave_form.get_format_chunk()   file "/usr/lib/python2.7/site-packages/pyglet/media/riff.py", line 174, in get_format_chunk     chunk in self.get_chunks():   file "/usr/lib/python2.7/site-packages/pyglet/media/riff.py", line 110, in get_chunks     chunk = cls(self.file, name, length, offset)   file "/usr/lib/python2.7/site-packages/pyglet/media/riff.py", line 155, in __init__     raise riffformatexception('size of format chunk incorrect.') pyglet.media.riff.riffformatexception: size of format chunk incorrect. al lib: releasealc: 1 device not closed 

you can use pyaudio. example here on linux works:

#!usr/bin/env python   #coding=utf-8    import pyaudio   import wave    #define stream chunk    chunk = 1024    #open wav format music   f = wave.open(r"/usr/share/sounds/alsa/rear_center.wav","rb")   #instantiate pyaudio   p = pyaudio.pyaudio()   #open stream   stream = p.open(format = p.get_format_from_width(f.getsampwidth()),                   channels = f.getnchannels(),                   rate = f.getframerate(),                   output = true)   #read data   data = f.readframes(chunk)    #play stream   while data:       stream.write(data)       data = f.readframes(chunk)    #stop stream   stream.stop_stream()   stream.close()    #close pyaudio   p.terminate()   

Comments