Python基于百度接口的语音识别

1.主要模块介绍

1)使用pyaudio模块来调用麦克风录制音频

2.pyaudio模块的安装

pip install pyaudio

3.使用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.获取语音识别结果

更多技术干货敬请关注,另有源码时代成都校区最新干货:

了解语音识别的原理;

学会应用语音识别解决实际工作问题;

Python基于百度接口的语音识别


分享到:


相關文章: