使用 Google Speech API 在 Python 中进行语音识别

pythonprogrammingserver side programming

语音识别是家庭自动化、AI 等多个应用中最有用的功能之一。在本节中,我们将了解如何使用 Python 和 Google 的 Speech API 进行语音识别。

在本例中,我们将使用麦克风提供音频以进行语音识别。要配置麦克风,需要一些参数。

要使用此模块,我们必须安装 SpeechRecognition 模块。还有另一个名为 pyaudio 的模块是可选的。使用它我们可以设置不同的音频模式。

sudo pip3 install SpeechRecognition
sudo apt-get install python3-pyaudio

对于外部麦克风或 USB 麦克风,我们需要提供准确的麦克风以避免任何困难。在Linux上,如果我们输入"lsusb"来显示USB设备的相关信息。

第二个参数是Chunk Size。使用它我们可以指定我们想要一次读取多少数据。它将是一个 2 的幂的数字,例如 1024 或 2048 等。

我们还必须指定采样率来确定记录数据进行处理的频率。

由于周围环境中可能存在一些不可避免的噪音,因此我们必须调整环境噪音以获取准确的声音。

识别语音的步骤

  • 获取不同麦克风的相关信息。

  • 使用块大小、采样率、环境噪音调整等配置麦克风。

  • 等待一段时间以获取语音

    • 识别语音后,尝试将其转换为文本,否则会引发一些错误。

  • 停止过程。

示例代码

import Speech_recognition as spreg
#设置采样率和数据大小
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
$ 

相关文章