使用 Google 語音 API 的 Python 語音識別
語音識別是許多應用(如家庭自動化、人工智慧等)中最有用的功能之一。在本節中,我們將瞭解如何使用 Python 和 Google 的語音 API 來實現語音識別。
在本例中,我們將使用麥克風輸入音訊進行語音識別。要配置麥克風,需要一些引數。
要使用此模組,我們必須安裝 SpeechRecognition 模組。還有一個名為 pyaudio 的可選模組。使用它我們可以設定不同的音訊模式。
sudo pip3 install SpeechRecognition sudo apt-get install python3-pyaudio
對於外接麥克風或 USB 麥克風,我們需要提供精確的麥克風以避免任何困難。在 Linux 上,如果我們鍵入“lsusb”則會顯示 USB 裝置的相關資訊。
第二個引數是塊大小。使用它我們可以指定一次讀取多少資料。它將是一個 2 的冪的數字,例如 1024 或 2048 等。
我們還需要指定取樣率,以確定多久記錄一次資料以進行處理。
由於周圍環境中可能存在一些不可避免的噪音,因此我們必須調整環境噪音以獲取精確的語音。
語音識別步驟
獲取不同的麥克風相關資訊。
使用塊大小、取樣率、環境噪聲調整等配置麥克風。
等待一段時間以獲取語音
當識別到語音時,嘗試將其轉換為文字,否則引發一些錯誤。
停止程序。
示例程式碼
import speech_recognition as spreg
#Setup the sampling rate and the data size
sample_rate = 48000
data_size = 8192
recog = spreg.Recognizer()
with spreg.Microphone(sample_rate = sample_rate, chunk_size = data_size) as source:
recog.adjust_for_ambient_noise(source)
print('Tell Something: ')
speech = recog.listen(source)
try:
text = recog.recognize_google(speech)
print('You have said: ' + text)
except spreg.UnknownValueError:
print('Unable to recognize the audio')
except spreg.RequestError as e:
print("Request error from Google Speech Recognition service; {}".format(e))
輸出
$ python3 318.speech_recognition.py Tell Something: You have said: here we are considering the asymptotic notation Pico to calculate the upper bound of the time complexity so then the definition of the big O notation is like this one $
在不使用麥克風的情況下,我們還可以將某些音訊檔案作為輸入以將其轉換為語音。
示例程式碼
import speech_recognition as spreg
sound_file = 'sample_audio.wav'
recog = spreg.Recognizer()
with spreg.AudioFile(sound_file) as source:
speech = recog.record(source) #use record instead of listning
try:
text = recog.recognize_google(speech)
print('The file contains: ' + text)
except spreg.UnknownValueError:
print('Unable to recognize the audio')
except spreg.RequestError as e:
print("Request error from Google Speech Recognition service; {}".format(e))
輸出
$ python3 318a.speech_recognition_file.py The file contains: staying ahead of the curve demand planning new technology it also helps you progress in your career $
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP