Python 中的实时离线语音识别可以使用各种库和技术来实现。在本文中,我们将探讨解决此问题的三种不同选择。


方法1:使用 SpeechRecognition 库

SpeechRecognition 库提供了一种简单方便的方法,用于在 Python 中执行语音识别。它支持多种语音识别引擎,包括 Google Speech Recognition, Sphinx, and Wit.ai.

import speech_recognition as sr

# Initialize the recognizer
r = sr.Recognizer()

# Use the microphone as the audio source
with sr.Microphone() as source:
    print("Listening...")
    audio = r.listen(source)

# Recognize speech using Google Speech Recognition
try:
    print("Recognizing...")
    text = r.recognize_google(audio)
    print("You said:", text)
except sr.UnknownValueError:
    print("Could not understand audio")
except sr.RequestError as e:
    print("Could not request results from Google Speech Recognition service; {0}".format(e))

此代码片段使用 SpeechRecognition 库来收听来自麦克风的音频输入,并使用 Google 语音识别识别来识别语音。它处理无法理解音频或识别服务中出现错误的情况的异常。

方法 2:使用 PocketSphinx 库

如果您更喜欢离线语音识别解决方案,则可以使用 PocketSphinx 库。它是一个轻量级且高效的库,使用隐马尔可夫模型执行语音识别。

import speech_recognition as sr

# Initialize the recognizer
r = sr.Recognizer()

# Use the microphone as the audio source
with sr.Microphone() as source:
    print("Listening...")
    audio = r.listen(source)

# Recognize speech using PocketSphinx
try:
    print("Recognizing...")
    text = r.recognize_sphinx(audio)
    print("You said:", text)
except sr.UnknownValueError:
    print("Could not understand audio")
except sr.RequestError as e:
    print("Sphinx error; {0}".format(e))

此代码片段使用 PocketSphinx 库执行脱机语音识别。它监听来自麦克风的音频输入,并使用隐马尔可夫模型识别语音。与上一个选项类似,它会在无法理解音频或识别过程中出现错误的情况下处理异常。

选项 3:使用 DeepSpeech 库

如果您需要更准确、更高级的语音识别,可以使用 DeepSpeech 库。它是由Mozilla开发的开源库,利用深度学习技术来实现最先进的语音识别性能。

import deepspeech

# Initialize the DeepSpeech model
model = deepspeech.Model('path/to/deepspeech/model.pb')

# Use the microphone as the audio source
with sr.Microphone() as source:
    print("Listening...")
    audio = r.listen(source)

# Recognize speech using DeepSpeech
try:
    print("Recognizing...")
    text = model.stt(audio.get_raw_data())
    print("You said:", text)
except sr.UnknownValueError:
    print("Could not understand audio")
except sr.RequestError as e:
    print("DeepSpeech error; {0}".format(e))

此代码片段使用 DeepSpeech 库来执行高级语音识别。它使用预训练模型文件的路径初始化 DeepSpeech 模型,并侦听来自麦克风的音频输入。然后,它使用 DeepSpeech 模型识别语音并打印识别的文本。与前面的选项类似,它会处理无法理解音频或识别过程中出现错误的情况的异常。

在这三个选项中,选择取决于您的具体要求。如果您需要一个简单方便的在线语音识别解决方案,使用 SpeechRecognition 库的选项 1 是一个不错的选择。如果您更喜欢具有轻量级和高效识别的离线解决方案,则使用 PocketSphinx 库的选项 2 是合适的。为了获得更高级和更准确的语音识别,建议使用 DeepSpeech 库的选项 3。

归根结底,最佳选择取决于具体用例以及准确性、便利性和离线能力之间的权衡。