Play wav file python 3

二次信任 提交于 2020-01-25 18:40:09

问题


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.


回答1:


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')



回答2:


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)



回答3:


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}')


来源:https://stackoverflow.com/questions/25462213/play-wav-file-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!