如何更改语音识别的输出语言

时间:2019-05-09 09:10:41

标签: python python-3.x speech-recognition cjk google-speech-api

此代码有效,但是我只能听englsih输出语音,我想将输出语音语言更改为Chinese。该代码可以识别中文,但输出不是中文,并且我不能离线使用pyttsx3识别中文,这对修复代码有帮助吗? 这是我的代码

import aiml
import os
import time
import argparse

mode = "text"
voice = "pyttsx3"
terminate = ['bye', 'buy', 'shutdown', 'exit', 'quit', 'gotosleep', 'goodbye']


def get_arguments():
    parser = argparse.ArgumentParser()
    optional = parser.add_argument_group('params')
    optional.add_argument('-v', '--voice', action='store_true', required=False,
                          help='Enable voice mode')
    optional.add_argument('-g', '--gtts', action='store_true', required=False,
                          help='Enable Google Text To Speech engine')
    arguments = parser.parse_args()
    return arguments


def gtts_speak(XiaoZhi_speech):
    tts = gTTS(text=XiaoZhi_speech, lang='zh-TW')
    tts.save('XiaoZhi_speech.mp3')
    mixer.init()
    mixer.music.load('XiaoZhi_speech.mp3')
    mixer.music.play()
    while mixer.music.get_busy():
        time.sleep(1)


def offline_speak(XiaoZhi_speech):
     engine = pyttsx3.init()
     engine.say(XiaoZhi_speech)
     engine.runAndWait()


def speak(XiaoZhi_speech):
    if voice == "gTTS":
        gtts_speak(XiaoZhi_speech)
    else:
        offline_speak(XiaoZhi_speech)


def listen():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Talk to X.I.A.O.Z.H.I: ")
        audio = r.listen(source)
    try:
        print(r.recognize_google(audio,language="zh-TW" ))
        return r.recognize_google(audio)
    except sr.UnknownValueError:
        speak(
            "I couldn't understand what you said! Would you like to repeat?")
        return(listen())
    except sr.RequestError as e:
        print("Could not request results from " +
              "Google Speech Recognition service; {0}".format(e))


if __name__ == '__main__':
    args = get_arguments()

    if (args.voice):
        try:
            import speech_recognition as sr
            mode = "voice"
        except ImportError:
            print("\nInstall SpeechRecognition to use this feature." +
                  "\nStarting text mode\n")
    ```

0 个答案:

没有答案