在本文中,我们将使用 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中文网其他相关文章!