我正在研究根据键盘输入从计算机播放声音的代码。声音存储为 wav 文件并使用 PyAudio 播放。然而,两次连续的键盘敲击播放的声音之间的延迟太慢了,所以我试图添加线程来加快 I/O 时间。但是,音频现在发出沙哑的声音,我认为线程上的锁不起作用。以下是相关代码:
while threading.activeCount() < NUM_THREADS:
message, delta_time = midi_in.get_message()
if message:
if message[2] == 0:
continue
elif message and (str(message[1]) == "108" or str(message[1]) == "107"):
break
else:
t = threading.Thread(target=play, args=(message,))
lock = threading.Lock()
lock.acquire()
t.start()
lock.release()
def play(message):
WAVE_FILENAME = "final"+str(message[1]) + '.wav'
CHUNK = 1024
wf = wave.open(WAVE_FILENAME)
p = pyaudio.PyAudio()
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)
stream.stop_stream()
stream.close()
p.terminate()
非常感谢你的帮助!