语音识别之调用googel和IBM的api
1.模块介绍
近期在语音识别的过程中还了解到python 中有一个SpeechRecognition包,它集合了几个语音识别库的接口,非常实用,这里就给大家介绍一下它的模块、调用。由于之前已经写过该模块的安装了,所以在这里就不再赘述了。这里需要说明的是,我的整个测试是在win10系统上的jupyter notebook书写完成,且python环境为3.6.2。
其它python版本未作测试。
2.SR模块之recognize_google的使用(调用google语音识别api)
想要实现可以调用google的api接口,顾名思义,需要科学上网,嘿嘿嘿~~
import speech_recognition as sr #引入语音识别包
ddir #查看当前文件夹
r=sr.Recognizer()
print(sr.__version__)
#显示当前sr的版本号
#读入本地wav文件
harvard=sr.AudioFile('audio_files\harvard.wav')
with harvard as source:
audio=r.record(source)
#输出audio文件类型
type(audio)
其显示的结果为:AudioData,如下所示:
特别说明的是,这里我采用的是with as的语法读取文件,该方式比一般的方式有一个好的优点就是不用再去关闭对于文件的操作。
text=r.recognize_google(audio)
print(text)
在这里我们即可看到google api识别后的结果
文字结果如下所示:
the stale smell of old beer lingers
it takes heat to bring out the odor a cold dip restores health
and zest a salt pickle taste fine with ham tacos al Pastore are
my favorite a zestful food is be hot cross bun
3.IBM语音识别库ibm_watson的安装及使用
3.1 安装ibm_watson
pip install --upgrade ibm-watson
因为我的之前已经编辑过了,所以就直接显示安装成功了。
3.2 申请IBM-Cloud账号
由于我们需要调用IBM-cloud的speech to text的api,所以我们需要提供一个IBM提供给的api和url来进行认证。
步骤:
1.注册ibm-cloud账号
2.创建一个Speech to text服务实例
3.复制得到该服务实例的api和url
完成之后你将会得到这样一个界面:
3.3测试实例
为了测试这个文件,我又新建了一个jupyter notebook来测试其ibm的语音识别结果。
#首先先引入必要的库
import json
from os.path import join, dirname
from ibm_watson import SpeechToTextV1
from ibm_watson.websocket import RecognizeCallback, AudioSource
import threading
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
在下边的部分添加刚刚申请的api和url认证链接
authenticator = IAMAuthenticator('your_api_key')
#这里放入api
service = SpeechToTextV1(authenticator=authenticator)
service.set_service_url('https://stream.watsonplatform.net/speech-to-text/api')
#这里放入url
该部分配置文件,旨在打印配置信息,其主要就是打印出所有支持的模式,例如我们此处使用的是en-US_BroadbandModel 模式,我们还可以根据打印结果自己选择适合的模式。
#打印配置信息,模式选择
models = service.list_models().get_result()
print(json.dumps(models, indent=2))
model = service.get_model('en-US_BroadbandModel').get_result()
print(json.dumps(model, indent=2))
开始读取本地的wav文件,并且调用IBM的api进行语音识别,识别结果返回为json文件。
#读取指定文件
filename='audio_files\harvard.wav'
with open (filename,'rb') as audio_file:
print(json.dumps(
service.recognize(
audio=audio_file,
content_type='audio/wav',
timestamps=True,
word_confidence=True).get_result(),
indent=2))
最后其识别结果就会包装成json文件返回回来,如下所示:
整理可得,其最后的识别结果为:
the stale smell of old beer lingers it takes heat to bring out
the odor a cold dip restores health invest
a salt pickle tastes fine with him tacos al pastore
are my favourite a zest for food is the hot cross bun.
这里我要来介绍一下,ibm-watson的api返回的结果代表的含义,每识别一个语音信号,就会返回三条信息,分别表示识别结果、起始和结束时刻(单位为秒/s)。如下所示:
4.总结
在这篇博客中,我分别调用了google和IBM的api进行指定wav文件的语音识别,单从识别结果来看的话,二者识别结果一样,但是在时间效率上,我还是感觉IBM的速度较快,当然google的识别也有可能是因为科学上网速度的限制,其中结果无从得知。
当然,此次结果我也是清楚的认识到,其它外边的一些大公司已经将语音识别做到如此地步,也对于自己后续的语音识别工作提供了一个底数。