gpt4 book ai didi

python-3.x - 如何使用Python中的语音识别自动检测语言

转载 作者:行者123 更新时间:2023-12-03 00:11:54 25 4
gpt4 key购买 nike

我正在开发一个应用程序,我想自动检测语言,然后打印它。
我的代码:

with sr.Microphone() as source:
audio = r.listen(source)
try:
# Auto detect the language
print("You said: " + r.recognize_google(audio))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service")
希望你能理解。

最佳答案

对于您的答案来说可能为时已晚。但是,将来可能会有其他人在寻找。
我还没有找到一种使用Speech_recognition自动检测语言的方法。 Google API确实以备用语言数组的形式支持多种语言,它将尝试使用您指定的其他语言来提供翻译。
我克服了检测语言的问题的方式是,我只有两种语言。我可以拥有更多,而我只有两个。我使用唤醒词和命令。因此,我可以说(例如)“可以从西类牙语翻译计算机”,并且命令解析器确定意图是从西类牙语翻译。我为此使用了剪裁,但是您可以执行字符串标记化。无论如何,在那一点上,因为我知道目的是“来自西类牙语”,所以我将语言代码显式设置为“es”,如下所示:

 said = r.recognize_google(audio, language="es")
我的SpeechRecord类
import speech_recognition as sr

class SpeechRec:
#https://techwithtim.net/tutorials/voice-assistant/wake-keyword/
def record(self, lang='en'):
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""

try:
#can I detect the language?
if (lang == 'en') :
said = r.recognize_google(audio, language='en-US')
elif (lang == 'es') :
said = r.recognize_google(audio, language="es")

print(said)
except Exception as e:
if (str(e) != ""):
print("Exception: " + str(e))

return said.lower()
监听循环-我从Flask事件中调用它,但在独立应用程序中它的作用相同
WAKE = "computer"
while True:
text = SpeechRec().record()
language = "en"

if text.count(WAKE) > 0:
text = SpeechRec().record()

#here I have a call to determine the intent via Snips - I've removed that and just
#placed a text comparison for simplicity. Also, to note, using Snips I can reduce
#the wake word and command to remove two of these
#"text = SpeechRec().record()" lines
if (text == 'translate from spanish'):
text = SpeechRec().record('es')
else:
text = SpeechRec().record()

#at this point I do the translation and print the value from the translation
这可能不是最优雅的解决方案。将来我可能会多次重写。但是,它可以满足我目前的需求。
我希望这有助于回答您的问题。

关于python-3.x - 如何使用Python中的语音识别自动检测语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63005440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com