使用pyaudio紧接着播放文件

时间:2017-12-06 22:50:07

标签: python text-to-speech pyaudio wave

我试图修改我的第一个Python程序。我尝试使用this repository做一些基本的文字转语音。它确实很好,但我想改进它。

从它的外观来看,播放的样本之间有0.145秒的延迟。然而,并非所有的声音样本都是0.145秒,我想让每个样本一个接一个播放,没有延迟或跳过。

import re
import wave
import pyaudio
import _thread
import time

class TextToSpeech:

    CHUNK = 1024

    def __init__(self, words_pron_dict:str = 'cmudict-0.7b.txt'):
        self._l = {}
        self._load_words(words_pron_dict)

    def _load_words(self, words_pron_dict:str):
        with open(words_pron_dict, 'r') as file:
            for line in file:
                if not line.startswith(';;;'):
                    key, val = line.split('  ',2)
                    self._l[key] = re.findall(r"[A-Z]+",val)

    def get_pronunciation(self, str_input):
        list_pron = []
        for word in re.findall(r"[\w']+",str_input.upper()):
            if word in self._l:
                list_pron += self._l[word]
        print(list_pron)
        delay = 0.0
        for pron in list_pron:
            _thread.start_new_thread( TextToSpeech._play_audio, (pron,delay,))
            delay += 0.145

    def _play_audio(sound, delay):
        try:
            time.sleep(delay)
            wf = wave.open("sounds/"+sound+".wav", 'rb')
            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(TextToSpeech.CHUNK)

            while data:
                stream.write(data)
                data = wf.readframes(TextToSpeech.CHUNK)

            stream.stop_stream()
            stream.close()

            p.terminate()
        except:
            pass




if __name__ == '__main__':
    tts = TextToSpeech()
    while True:
        tts.get_pronunciation(input('Enter a word or phrase: '))

我已经尝试摆脱线程和延迟,但样本之间仍有一些延迟。我认为我应该,而不是将延迟递增0.145,而是以秒为单位递增样本的长度,但我已经查看了pyaudio文档,我不知道如何做到这一点。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

这是一个经过修改的代码,可以连续播放wav文件。

import re
import wave
import pyaudio

class TextToSpeech:

    CHUNK = 1024

    def __init__(self, words_pron_dict='cmudict-0.7b.txt'):
        self._l = {}
        self._load_words(words_pron_dict)

    def _load_words(self, words_pron_dict: str):
        with open(words_pron_dict, 'r') as file:
            for line in file:
                if not line.startswith(';;;'):
                    key, val = line.split('  ', 2)
                    self._l[key] = re.findall(r"[A-Z]+", val)

    def get_pronunciation(self, str_input):
        list_pron = []
        for word in re.findall(r"[\w']+", str_input.upper()):
            if word in self._l:
                list_pron += self._l[word]
        print(list_pron)

        # pyaudio set up.
        # This open method assume all wave files have the same format.
        p = pyaudio.PyAudio()
        stream = p.open(format=p.get_format_from_width(2),
                        channels=2,
                        rate=44100,
                        output=True,
                        frames_per_buffer=self.CHUNK)

        # play each wav file contineuously
        for pron in list_pron:
            with wave.open("sounds/"+pron+".wav", 'rb') as wf:
                data = wf.readframes(TextToSpeech.CHUNK)
                while data:
                    stream.write(data)
                    data = wf.readframes(TextToSpeech.CHUNK)

        stream.stop_stream()
        stream.close()
        p.terminate()

if __name__ == '__main__':
    tts = TextToSpeech()
    while True:
        tts.get_pronunciation(input('Enter a word or phrase: '))