在本文中,我們將使用 Google 翻譯 API 使用 Python 建立一個語音翻譯器
安裝(Linux):
— pip install SpeechRecognition
— pip install googletrans
— pip install gTTS
— pip install Playsound
安裝(Windows):
— pip install SpeechRecognition
— pip install gTTS
— pip install pipwin
— pipwin 安裝 pyaudio
— pip install Playsound==1.2.2
— pip install googletrans==4.0.0-rc1
讓我們導入所需的模組
import speech_recognition as sr from googletrans import Translator from gtts import gTTS from playsound import playsound
建立翻譯器類別的物件
translator = Translator()
我們現在將使用預設麥克風作為音訊來源,聆聽短語並將其提取到音訊資料
r = sr.Recognizer() with sr.Microphone() as source: print("Speak Now:") audio = r.listen(source)
設定目標語言,您可以在這裡取得所有語言程式碼的清單 [https://meta.wikimedia.org/wiki/Template:List_of_language_names_ordered_by_code]
language_to_translate='en'
下面的部分將列印辨識的語音,設定要翻譯的語言並使用 google API 來翻譯辨識的語音。我們還將在控制台上列印檢測到的文字和翻譯後的文字
print("Recognized as: ", r.recognize_google(audio)) language = language_to_translate translations = translator.translate(r.recognize_google(audio), dest=language) print(translations.origin, ' -> ', translations.text)
最後我們將使用Google Text-to-Speech 將翻譯後的文字儲存為mp3 音訊文件,然後使用playsound 庫播放它
myobj = gTTS(text=translations.text, lang=language) myobj.save(tr + ".mp3") playsound(tr + ".mp3")
*完整程式碼:
*
import speech_recognition as sr from googletrans import Translator from gtts import gTTS from playsound import playsound translator = Translator() r = sr.Recognizer() with sr.Microphone() as source: print("Speak Now:") audio = r.listen(source) language_to_translate='en' try: print("Recognized as: ", r.recognize_google(audio)) language = language_to_translate translations = translator.translate(r.recognize_google(audio), dest=language) print(translations.origin, ' -> ', translations.text) myobj = gTTS(text=translations.text, lang=language) myobj.save(tr + ".mp3") playsound(tr + ".mp3") except Exception as e: print(e)
以上是使用 Python 和 Google Translate API 將語音翻譯為任何語言(Google 支援)的詳細內容。更多資訊請關注PHP中文網其他相關文章!