使用Python進行語音辨識(聲音轉文字)

Yanwei Liu
4 min readJun 27, 2019

安裝套件:

$ pip install SpeechRecognition
$ pip install pocketsphinx #使用CMU Sphinx才需要安裝

使用:

使用Google的服務(有聲音時間限制,不確定幾分鐘,且須連網)

import speech_recognition as sr
r = sr.Recognizer() #預設辨識英文
with sr.WavFile("XXXXX.wav") as source: #讀取wav檔
audio = r.record(source)
try:
print("Transcription: " + r.recognize_google(audio,language="zh-TW"))
#使用Google的服務
except LookupError:
print("Could not understand audio")

使用CMU Sphinx的服務(可免費離線使用)

import speech_recognition as sr
r = sr.Recognizer() #預設辨識英文
with sr.WavFile("XXXXX.wav") as source: #讀取wav檔
audio = r.record(source)
try:
print("Transcription: " + r.recognize_sphinx(audio))
#使用Google的服務
except LookupError:
print("Could not understand audio")

API介紹:

r.record(source, duration=10)           #只錄10秒作為辨識內容
r.record(source, offset=4, duration=10) #跳過開頭4秒後,開始錄10秒作為辨識內容
r = r.adjust_for_ambient_noise(source) #降低噪音造成的辨識干擾

如果要搭配電腦麥克風使用:

https://realpython.com/python-speech-recognition/#working-with-microphones

--

--