使用Python播放音频并获得当前播放秒数?

2024-10-03 02:36:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python开发语音接口。我的音频播放有问题

你用什么黑背简单的mp3文件在树莓皮

我需要播放音频,在播放结束前2秒,我需要开始另一项任务(打开麦克风流) 如何存档此文件?可能的问题是,我还没有找到读取当前播放秒数的方法。如果我能读到这篇文章,我会在currenttime为audiolength-2秒时启动一个新线程

我希望你能帮助我,或者你有这方面的经验


Tags: 文件方法语音经验音频线程mp3树莓
1条回答
网友
1楼 · 发布于 2024-10-03 02:36:20

我找到了解决办法。 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

希望它能帮助别人, 亚历克斯

相关问题 更多 >