语音交流是最常见的交流方式,世界上大多数人都通过说话进行交流。语音API识别系统能将大家说的话转化成文本。我们的生活中有很多语音识别系统,例如苹果公司的 SIRI 可以识别语音并将其转换成文本。
语音识别的工作原理
语音识别过程
隐马尔可夫模型(HMM)是一种深度神经网络模型,常被用来将音频转换为文本。本文不阐述语音转换过程的具体细节,主要演示如何用 Python 将语音转换成文本,主要通过“语音识别” API 和 “PyAudio” 库来实现。
语音识别 API 同时支持多个 API,本文使用的是谷歌的语音识别 API。更多细节请点击这里进行查看。谷歌语音识别 API 可以将语音转换为文本。
Python库
!pip install SpeechRecognition
将音频文件转换为文本
步骤
-
导入语音识别库
-
初始化识别器类以便识别语音。我们用的是谷歌语音识别。
-
语音识别支持的音频文件格式:wav、AIFF、AIFF-C、FLAC。我本示例中使用的是 “wav” 文件。
-
我使用了电影 ‘taken’ 中的音频片段,内容是电影中的台词:“I don’t know who you are I don’t know what you want if you’re looking for ransom I can tell you I don’t have money (我不知道你是谁,我不知道你想要什么,如果你想要赎金,我可以告诉你,我没有钱)”。
-
谷歌识别器的默认识别语言是英语,但它可以识别其他语言,更多信息请查看查看此文档。
代码
#import library
import speech_recognition as sr
# Initialize recognizer class (for recognizing the speech)
r = sr.Recognizer()
# Reading Audio file as source
# listening the audio file and store in audio_text variable
with sr.AudioFile('I-dont-know.wav') as source:
audio_text = r.listen(source)
# recoginize_() method will throw a request error if the API is unreachable, hence using exception handling
try:
# using google speech recognition
text = r.recognize_google(audio_text)
print('Converting audio transcripts into text ...')
print(text)
except:
print('Sorry.. run again...')
输出
转换非英语音频
例如,如果我们想读取一个法语音频文件,就需要在 recogonize_google 中添加语言选项,其余代码保持不变。更多细节请参考文档。
#Adding french langauge option
text = r.recognize_google(audio_text, language = "fr-FR")
输出
把麦克风语音转换为文本
步骤
- 安装 PyAudio 库,PyAudio 库通过麦克风和扬声器接收音频输入和输出。它通常从麦克风中获得声音。
!pip install PyAudio
- 这里我们不使用音频文件源,而是使用麦克风类,其他步骤都一样。
代码
#import library
import speech_recognition as sr
# Initialize recognizer class (for recognizing the speech)
r = sr.Recognizer()
# Reading Microphone as source
# listening the speech and store in audio_text variable
with sr.Microphone() as source:
print("Talk")
audio_text = r.listen(source)
print("Time over, thanks")
# recoginize_() method will throw a request error if the API is unreachable, hence using exception handling
try:
# using google speech recognition
print("Text: "+r.recognize_google(audio_text))
except:
print("Sorry, I did not get that")
我只说了一句“How are you? (你好吗?)”
输出
转换非英语语音
我们同样要在 recognition_google() 中添加相应的语言选项。我正用印度泰米尔语交谈,并且在语言选项中添加了“ta-IN”。
# Adding "tamil language"
print(“Text: “+r.recognize_google(audio_text, language = “ta-IN”))
我用泰米尔语说“你好吗”,识别器就准确地打出了泰米尔语的文本。
输出
注意:
谷歌语音识别 API 是一种把语音转换为文本的简单方法,但它只能有有网络的情况下使用。
本文我们学习了如何用谷歌语音识别 API 将语音转换成文本,这对 NLP 项目尤其是处理音频转录数据方面非常有用。如果大家有任何补充内容,请在下方评论区写出来哦~
感谢大家的阅读。
原文作者:Dhilip Subramanian
原文链接:https://towardsdatascience.com/easy-speech-to-text-with-python-3df0d973b426