我尝试播放.wav文件一段随机的毫秒数,然后再继续我的代码中的下一个文件。这样做的最佳方式是什么?
我目前有以下代码:
#!/usr/bin/env python
from random import randint
import time
import pyaudio
import wave
while True:
# random number to indicate wav file name
x = randint(1,45)
print ("Note: %d" % x)
# play wav file
chunk = 1024
f = wave.open(r"%d.wav" % x,"rb")
p = pyaudio.PyAudio()
stream = p.open(format = p.get_format_from_width(f.getsampwidth()),
channels = f.getnchannels(),
rate = f.getframerate(),
output = True)
data = f.readframes(chunk)
while data != '':
stream.write(data)
data = f.readframes(chunk)
stream.stop_stream()
stream.close()
p.terminate()
答案 0 :(得分:0)
试试这个,不确定它是否干净但代码是否正常。
#!/usr/bin/env python
from random import randint
import time
import pyaudio
import threading
import multiprocessing
import wave
# play wav file
chunk = 1024
def playAudio(x):
f = wave.open(r"%d.wav" % x,"rb")
p = pyaudio.PyAudio()
stream = p.open(format = p.get_format_from_width(f.getsampwidth()),
channels = f.getnchannels(),
rate = f.getframerate(),
output = True)
data = f.readframes(chunk)
while data != '':
stream.write(data)
data = f.readframes(chunk)
stream.stop_stream()
stream.close()
p.terminate()
if __name__ == '__main__':
while True:
x = randint(1,45)
p = multiprocessing.Process(target=playAudio, args=(x,))
p.start()
time.sleep(5)
p.terminate()
p.join()