Search code examples
audiopython-3.xexewav

Play wav file python 3


I want to play a .wav file in Python 3.4. Additonally, I want python to play the file rather than python open the file to play in VLC, media player etc..

As a follow up question, is there any way for me to combine the .wav file and the .py file into a standalone exe.

Ignore the second part of the question if it is stupid, I don't really know anything about compiling python.

Also, I know there have been other questions about .wav files, but I have not found one that works in python 3.4 in the way I described.


Solution

  • I fixed the problem by using the module pyaudio, and the module wave to read the file. I will type example code to play a simple wave file.

    import wave, sys, pyaudio
    wf = wave.open('Sound1.wav')
    p = pyaudio.PyAudio()
    chunk = 1024
    stream = p.open(format =
                    p.get_format_from_width(wf.getsampwidth()),
                    channels = wf.getnchannels(),
                    rate = wf.getframerate(),
                    output = True)
    data = wf.readframes(chunk)
    while data != '':
        stream.write(data)
        data = wf.readframes(chunk)