我正在使用python开发语音接口。我在播放音频时遇到问题。
您如何使用黑莓Raspberry Pi上的简单mp3文件?
我需要播放音频,并且在播放结束前2秒,我需要启动另一个任务(打开麦克风流)我该如何存档?可能的问题是,我还没有找到读取当前播放秒数的方法。如果我能读懂这篇文章,我会在当前时间为audiolength-2秒时启动一个新线程。
我希望您能为我提供帮助或对此有任何经验。
我找到了解决方案。PyAudio提供了一种逐块播放音频的方法。通过该操作,您可以读取当前块并将其与音频的整体大小进行比较。
class AudioPlayer():
"""AudioPlayer class"""
def __init__(self):
self.chunk = 1024
self.audio = pyaudio.PyAudio()
self._running = True
def play(self, audiopath):
self._running = True
#storing how much we have read already
self.chunktotal = 0
wf = wave.open(audiopath, 'rb')
stream = self.audio.open(format =self.audio.get_format_from_width(wf.getsampwidth()),channels = wf.getnchannels(),rate = wf.getframerate(),output = True)
print(wf.getframerate())
# read data (based on the chunk size)
data = wf.readframes(self.chunk)
#THIS IS THE TOTAL LENGTH OF THE AUDIO
audiolength = wf.getnframes() / float(wf.getframerate())
while self._running:
if data != '':
stream.write(data)
self.chunktotal = self.chunktotal + self.chunk
#calculating the percentage
percentage = (self.chunktotal/wf.getnframes())*100
#calculating the current seconds
current_seconds = self.chunktotal/float(wf.getframerate())
data = wf.readframes(self.chunk)
if data == b'':
break
# cleanup stream
stream.close()
def stop(self):
self._running = False
希望它可以帮助某人,亚历克斯