📜  语音翻译python代码示例

📅  最后修改于: 2022-03-11 14:46:56.481000             🧑  作者: Mango

代码示例1
from pyttsx3 import engine
import speech_recognition as sr
from google_trans_new import google_translator
import pyttsx3

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

recognizer = sr.Recognizer()
engine = pyttsx3.init()

with sr.Microphone() as source:
    print("Please say something.")
    speak("Please say something.")
    recognizer.adjust_for_ambient_noise(source,duration=1)
    audio  = recognizer.listen(source,timeout=1)
    print("Done recording")
    speak("Done recording")


try:
    print("recognizing...")
    speak("recognizing...")
    result = recognizer.recognize_google(audio,language='en')
except Exception as ex:
    print(ex)
    speak(ex)


#Translation function
def trans():
    langinput = input("Type the language code you want to translate:")
    speak("Type the language code you want to translate:")
    translator = google_translator()
    translate_text = translator.translate(str(result),lang_tgt=str(langinput))
    print(translate_text)
    speak(translate_text)
    engine.say(str(translate_text))
    engine.runAndWait()
trans()