Python 3.7文本到语音转换仅使用IDLE编辑器播放一个音频文件,有时根本不播放音频

时间:2019-03-05 05:46:56

标签: audio text-to-speech python-3.7

我正在使用IDLE编辑器和Python 3.7,我想知道为什么我的代码没有依次播放多个音频文件,有时根本不播放音频:

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
        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()
        return
    except:
        pass

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

我有一个音频文件列表,将在运行代码时以一定顺序播放,具体取决于我键入的单词。代码没有错误,但是当我运行它时,当我输入一个单词时,它只会播放所需的第一个音频文件(例如:当我输入“ buy”时,它需要以下两种声音:“ b”和“ ie”一起播放),但它只播放第一个声音“ b”,有时根本不播放声音。

为什么不播放多个音频文件?我知道很多人都遇到了这个问题,但是还没有解决。 谢谢您的提前帮助,非常感谢:)

0 个答案:

没有答案
相关问题