我正在尝试无限播放“ .wav”文件,以便在实验中使用。
我正在使用pyaudio网站(http://people.csail.mit.edu/hubert/pyaudio/)的脚本,但是它只播放了5秒钟。
我尝试使用下面的代码,但播放了几秒钟。
import pyaudio
import wave
while True:
CHUNK = 20*100
wf =
wave.open('Metano_Ref_Lockin=SR830_mod=0.460V_freq=3936_PP=20_NP=100.wav', 'rb')
data = wf.readframes(CHUNK)
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,
channels=wf.getnchannels(),
rate=wf.getframerate(),
output_device_index=4,
output=True)
while data != '':
stream.write(data)
data = wf.readframes(CHUNK)
stream.stop_stream()
stream.close()
p.terminate()
另一方面,此代码仍然有效,但是信号不一致(出现一些噪音)。
import pyaudio
import wave
CHUNK = 20*100
wf = wave.open('Metano_Ref_Lockin=SR830_mod=0.460V_freq=3936_PP=20_NP=100.wav', 'rb')
data = wf.readframes(CHUNK)
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,
channels=wf.getnchannels(),
rate=wf.getframerate(),
output_device_index=4,
output=True)
while data != '':
stream.write(data)
stream.stop_stream()
stream.close()
p.terminate()
我希望一个统一的信号可以无限地再现。 谢谢。
答案 0 :(得分:0)
您的数据比较应该是
while data != b'':
...
或更简单的变体(将空字符串强制转换为False
):
while data:
...
此外,您确实应该在循环之间重用wf
,stream
和p
:
import pyaudio
import wave
CHUNK = 2 ** 11
wf = wave.open('Metano_Ref_Lockin=SR830_mod=0.460V_freq=3936_PP=20_NP=100.wav', 'rb')
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
while True:
wf.rewind()
data = wf.readframes(CHUNK)
while data:
stream.write(data)
data = wf.readframes(CHUNK)
wf.close()
stream.stop_stream()
stream.close()
p.terminate()