075. 編寫一個函數,實現簡單的語音識別功能
- 075. 編寫一個函數,實現簡單的語音識別功能
-
- 安裝依賴庫
- 示例代碼
-
- 代碼說明
- 示例輸出
- 注意事項
- 使用 PocketSphinx 進行離線語音識別
-
- 注意事項
- 實現方法
-
- 使用SpeechRecognition庫實現語音識別
- 使用PyAudio和深度學習模型
- 使用Vosk離線識別引擎
- 使用百度語音API實現云端識別
- 使用Whisper模型實現轉錄
075. 編寫一個函數,實現簡單的語音識別功能
在 Python 中,可以使用 SpeechRecognition
庫來實現簡單的語音識別功能。SpeechRecognition
是一個流行的語音識別庫,支持多種語音識別引擎,包括 Google Web Speech API(在線)和本地引擎(如 PocketSphinx)。
使用 Google Web Speech API 來識別語音。
安裝依賴庫
在開始之前,請確保你已經安裝了 SpeechRecognition
庫。如果沒有安裝,可以通過以下命令安裝:
pip install SpeechRecognition
如果你需要使用本地引擎(如 PocketSphinx),還需要安裝 pocketsphinx
:
pip install pocketsphinx
示例代碼
以下代碼實現了一個簡單的語音識別函數,使用 Google Web Speech API 識別語音。
import speech_recognition as srdef simple_speech_recognition():# 創建一個 Recognizer 對象recognizer = sr.Recognizer()# 使用麥克風作為音頻源with sr.Microphone() as source:print("請說話...")audio = recognizer.listen(source) # 錄制音頻try:# 使用 Google Web Speech API 進行語音識別text = recognizer.recognize_google(audio, language="zh-CN") # 指定語言為中文print(f"您說的是: {text}")except sr.UnknownValueError:print("無法識別語音")except sr.RequestError as e:print(f"請求錯誤: {e}")# 示例用法
if __name__ == "__main__":simple_speech_recognition()
代碼說明
創建 Recognizer 對象:使用 speech_recognition.Recognizer()
創建一個識別器對象。
使用麥克風錄制音頻:
-
使用
sr.Microphone()
作為音頻源。 -
使用
recognizer.listen(source)
錄制音頻。
語音識別:
-
使用
recognizer.recognize_google(audio, language="zh-CN")
調用 Google Web Speech API 進行語音識別。 <