gpt4 book ai didi

python - 播放.wav文件x秒

转载 作者:行者123 更新时间:2023-12-03 02:10:20 25 4
gpt4 key购买 nike

在尝试进入我的代码中的下一个文件之前,我尝试随机播放.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()

最佳答案

尝试一下,不知道它是否是干净的代码,但是可以正常工作。

#!/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()

关于python - 播放.wav文件x秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24719108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com