目前正在使用 PyAudio 进行一些实验。我当前的目标是导入一个 wav 文件并让 PyAudio 为我播放它。播放它实际上是简单的部分 - 困难的部分是在 wav 文件完成后关闭流。现在我的代码永远不会退出 while 循环。我听到了 wav 文件,然后沉默了,因为代码继续不向流中写入任何内容。
import wave
import pyaudio
wav = wave.open('./5secondbeat.wav')
p = pyaudio.PyAudio()
chunk = 1024
stream = p.open(format = p.get_format_from_width(wav.getsampwidth()),
channels = wav.getnchannels(),
rate = wav.getframerate(),
frames_per_buffer = chunk,
output = True)
data = wav.readframes(chunk)
while data != '': //enters this loop
stream.write(data) //I hear my short 5 second wave file
data = wav.readframes(chunk)
print('hello') //this never gets printed and my code continues running in the loop
stream.close()
p.terminate()
我错过了什么?
最佳答案
条件中的数据类型不对应。在检查之前,您可以尝试其中一种将它们转换为相同类型:
while data != b'':
或
while data.decode("utf-8") != '':
关于python - wav 文件完成时 PyAudio readframes 未结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57282650/