原标题:Python基于百度接口的语音识别
1. 主要模块介绍
1) 使用pyaudio 模块来调用麦克风录制音频
2) 使用百度提供的密钥获取access_token
3) 使用百度的语音识别接口,识别语音
2.pyaudio模块的安装
pip install pyaudio3.使用pyaudio录制声音
Pyaudio主要用法:
主要列出pyaudio对象的open()方法的参数:
rate:采样率, 每秒使用多少bit对采样数据进行保存
channels:声道数
format:采样值的量化格式,值可以为paFloat32、paInt32、paInt24、paInt16、paInt8等。下面的例子中,使用paInt16.
input:输入流标志,Ture表示开始输入流
output:输出流标志
Pyaudio详细文档http://people.csail.mit.edu/hubert/pyaudio/docs/
下面为代码
def get_data_mic(): p = PyAudio() # 摁下任意键开始录音 input("摁下任意键开始5秒录音...") # 初始化麦克风设备参数,并开始采样 stream = p.open(format=paInt16, channels=1, rate=8000, input=True, frames_per_buffer=1024) # 声音采集数据缓存 frames = [] for x in range(0, int(8000/1024 * 5)): data = stream.read(1024) frames.append(data) print('* stop recorded') # 关闭设备 stream.stop_stream() stream.close() p.terminate() # 返回采集数据位二进制流字符 return b''.join(frames)
4.获取access_token
# 获取Access Token,通过api_key,secret_key获取def get_access_token(cltid, srt_key): oauth_url = 'https://openapi.baidu.com/oauth/2.0/token' args_data = {'grant_type': 'client_credentials', 'client_id': cltid, 'client_secret': srt_key, } cnt_type = {'Content-Type': 'application/json; charset=UTF-8'} resp = requests.post(oauth_url, data=args_data, headers=cnt_type) print("get baidu center info...") if resp.status_code != 200: print("have http error", resp.status_code) return None cnt = resp.json() # 获取的内容变为字典 cnt['expires_in'] += int(time.time()) # 将有效期时间记录 with open('baidu.ck', 'w', encoding='utf-8') as fp: res = {'access_token': cnt['access_token'], 'expires_in': cnt['expires_in']} json.dump(res, fp) return cnt['access_token']
5.获取语音识别结果
# 获取语音识别结果def get_text_fromsound(atoken): speed_url = 'http://vop.baidu.com/server_api' args_data = {'format': 'pcm', 'rate':8000, 'channel': 1, 'cuid': 'rocky_shop', # 应用名称,可随意取名 'token': atoken, } # 获取麦克风数据,按照百度文档要求,填写数据和长度 buf = get_data_mic() #此处是3定义的录音,返回值为二进制流字符 args_data['len'] = len(buf) args_data['speech'] = .b64encode(buf).decode() header = {'Content-Type': 'application/json'} resp = requests.post(speed_url, data=json.dumps(args_data), headers=header) info = resp.json() if info['err_no'] == 0: return info['result'] else: return [info['err_msg']]
更多技术干货敬请关注,另有源码时代成都校区最新干货:
了解语音识别的原理;
了解百度语音识别的应用场景;
学会应用语音识别解决实际工作问题;
责任编辑: