how to play wav file in python?

Posted on

Question :

how to play wav file in python?

I tried pygame for playing wav file like this:

import pygame

but It change the voice and I don’t know why!
I read this link solutions and can’t solve my problem with playing wave file!

for this solution I dont know what should I import?

s = Sound()'sound.wav')

and for this solution /dev/dsp dosen’t exist in new version of 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')
  from ossaudiodev import AFMT_S16_NE
except ImportError:
  if byteorder == "little":
    AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
    AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)

and when I tried pyglet It give me this error:

import pyglet

music ='mysound.wav')

nima@ca005 Desktop]$ python
Traceback (most recent call last):
  File "", line 4, in <module>
    music ='mysound.wav')
  File "/usr/lib/python2.7/site-packages/pyglet/", line 587, in media
    return media.load(path, streaming=streaming)
  File "/usr/lib/python2.7/site-packages/pyglet/media/", line 1386, in load
    source = _source_class(filename, file)
  File "/usr/lib/python2.7/site-packages/pyglet/media/", line 194, in __init__
    format = wave_form.get_format_chunk()
  File "/usr/lib/python2.7/site-packages/pyglet/media/", line 174, in get_format_chunk
    for chunk in self.get_chunks():
  File "/usr/lib/python2.7/site-packages/pyglet/media/", line 110, in get_chunks
    chunk = cls(self.file, name, length, offset)
  File "/usr/lib/python2.7/site-packages/pyglet/media/", line 155, in __init__
    raise RIFFFormatException('Size of format chunk is incorrect.') Size of format chunk is incorrect.
AL lib: ReleaseALC: 1 device not closed
Asked By: nim4n


Answer #1:

You can use PyAudio. An example here on my Linux it works:

#!usr/bin/env python  

import pyaudio  
import wave  

#define stream chunk   
chunk = 1024  

#open a wav format music  
f ="/usr/share/sounds/alsa/Rear_Center.wav","rb")  
#instantiate PyAudio  
p = pyaudio.PyAudio()  
#open stream  
stream = = 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:  
    data = f.readframes(chunk)  

#stop stream  

#close PyAudio  
Answered By: zhangyangyu

Answer #2:

The reason pygame changes your audio is mixer defaults to a 22k sample rate:

initialize the mixer module
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096): return None

Your wav is probably 8k. So when pygame plays it, it plays roughly twice as fast. So specify your wav frequency in the init.

Pyglet has some problems correctly reading RIFF headers. If you have a very basic wav file (with exactly a 16 byte fmt block) with no other information in the fmt chunk (like ‘fact’ data), it works. But it makes no provision for additional data in the chunks, so it’s really not adhering to the RIFF interface specification.

Answered By: Gene

Answer #3:

Works for me on Windows:

>>> from playsound import playsound
>>> playsound('/path/to/a/sound/file/you/want/to/play.wav')

NOTE: This has a bug in Windows where it doesn’t close the stream.
I’ve added a PR for a fix here:

Answered By: driedler

Answer #4:

PyGame has 2 different modules for playing sound and music, the pygame.mixer module and the module. This module contains classes for loading Sound objects and controlling playback. The difference is explained in the documentation:

The difference between the music playback and regular Sound playback is that the music is streamed, and never actually loaded all at once. The mixer system only supports a single music stream at once.

If you want to play a single wav file, you have to initialize the module and create a pygame.mixer.Sound() object from the file. Invoke play() to start playing the file. Finally, you have to wait for the file to play.

Use get_length() to get the length of the sound in seconds and wait for the sound to finish:
(The argument to pygame.time.wait() is in milliseconds)

import pygame

my_sound = pygame.mixer.Sound('mysound.wav')
pygame.time.wait(int(my_sound.get_length() * 1000))

Alternatively you can use pygame.mixer.get_busy to test if a sound is being mixed. Query the status of the mixer continuously in a loop:

import pygame

my_sound = pygame.mixer.Sound('mysound.wav')

while pygame.mixer.get_busy():
Answered By: Rabbid76

Leave a Reply

Your email address will not be published. Required fields are marked *