百度語音識別通過 REST API 的方式給開發(fā)者提供一個通用的 HTTP 接口,基于該接口,開發(fā)者可以輕松的獲取語音識別能力。SDK中只提供了PHP、C和JAVA的相關樣例,然而個人以為,使用Python開發(fā)難度更低,本文描述了簡單使用Python調用百度語音識別服務 REST API 的簡單樣例。
注冊開發(fā)者賬號和創(chuàng)建應用不再贅述,百度的REST API在調用過程基本分為三步:
- 獲取token
- 提交數(shù)據(jù)
- 處理JSON
獲取token
#Api_Key申請的api_key
#Secrect_Key對應的secret_key
url = 'https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id='+Api_Key+'&client_secret='+Secrect_Key
res = urllib2.urlopen(url).read()
data = json.loads(res)
token = data['access_token'] #獲取的token
print 'token獲取成功:'+`token`
提交數(shù)據(jù)
VOICE_RATE = 8000
WAVE_FILE = 'temp.wav'
USER_ID = 'duvoice'
WAVE_TYPE = 'wav'
#其它參數(shù)可參考sdk文檔
f = open(WAVE_FILE,'r')
speech = base64.b64encode(f.read())
size = os.path.getsize(WAVE_FILE)
update = json.dumps({'format':WAVE_TYPE,'rate':VOICE_RATE,'channel':1,'cuid':USER_ID,'token':token,'speech':speech,'len':size})
r = urllib2.urlopen(self.url,update)
處理JSON
t = r.read()
result = json.loads(t)
if result['err_msg']=='success.':
word = result['result'][0].encode('utf-8')
if word!='':
if word[len(word)-3:len(word)]==',':
print word[0:len(word)-3]
return word[0:len(word)-3]
else:
print word
return word
else:
print "音頻文件不存在或格式錯誤"
return ''
else:
print "錯誤"
經(jīng)過以上步驟便可提交一個wav文件進行解析,同時也可使用python的pyaudio庫進行錄音:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pyaudio import PyAudio, paInt16
import numpy as np
from datetime import datetime
import wave
class recoder:
NUM_SAMPLES = 2000 #pyaudio內置緩沖大小
SAMPLING_RATE = 8000 #取樣頻率
LEVEL = 500 #聲音保存的閾值
COUNT_NUM = 20 #NUM_SAMPLES個取樣之內出現(xiàn)COUNT_NUM個大于LEVEL的取樣則記錄聲音
SAVE_LENGTH = 8 #聲音記錄的最小長度:SAVE_LENGTH * NUM_SAMPLES 個取樣
TIME_COUNT = 60 #錄音時間,單位s
Voice_String = []
def savewav(self,filename):
wf = wave.open(filename, 'wb')
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(self.SAMPLING_RATE)
wf.writeframes("".join(self.Voice_String))
wf.close()
def recoder(self):
pa = PyAudio()
stream = pa.open(format=paInt16, channels=1, rate=self.SAMPLING_RATE, input=True,
frames_per_buffer=self.NUM_SAMPLES)
save_count = 0
save_buffer = []
time_count = self.TIME_COUNT
while True:
time_count -= 1
# print time_count
# 讀入NUM_SAMPLES個取樣
string_audio_data = stream.read(self.NUM_SAMPLES)
# 將讀入的數(shù)據(jù)轉換為數(shù)組
audio_data = np.fromstring(string_audio_data, dtype=np.short)
# 計算大于LEVEL的取樣的個數(shù)
large_sample_count = np.sum( audio_data > self.LEVEL )
print np.max(audio_data)
# 如果個數(shù)大于COUNT_NUM,則至少保存SAVE_LENGTH個塊
if large_sample_count > self.COUNT_NUM:
save_count = self.SAVE_LENGTH
else:
save_count -= 1
if save_count < 0:
save_count = 0
if save_count > 0 :
# 將要保存的數(shù)據(jù)存放到save_buffer中
#print save_count > 0 and time_count >0
save_buffer.append( string_audio_data )
else:
#print save_buffer
# 將save_buffer中的數(shù)據(jù)寫入WAV文件,WAV文件的文件名是保存的時刻
#print "debug"
if len(save_buffer) > 0 :
self.Voice_String = save_buffer
save_buffer = []
print "Recode a piece of voice successfully!"
return True
if time_count==0:
if len(save_buffer)>0:
self.Voice_String = save_buffer
save_buffer = []
print "Recode a piece of voice successfully!"
return True
else:
return False
|