0

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.

user2880853
  • 83
  • 2
  • 4
  • 8

3 Answers3

4

Using pyaudio you may get incorrect playback due to speed, consider instead:

sudo apt-get install python-pygame

Windows: choco install python-pygame?

def playSound(filename):
    pygame.mixer.music.load(filename)
    pygame.mixer.music.play()

import pygame
pygame.init()
playSound('hellyeah.wav')
Jonathan
  • 6,741
  • 7
  • 52
  • 69
3

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)
biertje72
  • 95
  • 7
user2880853
  • 83
  • 2
  • 4
  • 8
2

If you happen to be using linux a simple solution is to call aplay.

import os
wav_file = "./Hello.wav"
os.system(f'aplay {wav_file}')
John Forbes
  • 1,248
  • 14
  • 19