Python調(diào)用百度api實(shí)現(xiàn)語(yǔ)音識(shí)別詳解
最近在學(xué)習(xí)python,做一些python練習(xí)題
有一題是這樣的:
使用 Python 實(shí)現(xiàn):對(duì)著電腦吼一聲,自動(dòng)打開瀏覽器中的默認(rèn)網(wǎng)站。
例如,對(duì)著筆記本電腦吼一聲“百度”,瀏覽器自動(dòng)打開百度首頁(yè)。
然后開始search相應(yīng)的功能需要的模塊(windows10),理一下思路:
- 本地錄音
- 上傳錄音,獲得返回結(jié)果
- 組一個(gè)map,根據(jù)結(jié)果打開相應(yīng)的網(wǎng)頁(yè)
所需模塊:
- PyAudio:錄音接口
- wave:打開錄音文件并設(shè)置音頻參數(shù)
- requests:GET/POST
為什么要用百度語(yǔ)音識(shí)別api呢?因?yàn)槊赓M(fèi)試用。。

不多說(shuō),登錄百度云,創(chuàng)建應(yīng)用

查看文檔REST API文檔
文檔寫的蠻詳細(xì)的,簡(jiǎn)單概括就是
1.可以下載使用SDK

2.不需要下載使用SDK
選擇2.
- 根據(jù)文檔組裝url獲取token
- 處理本地音頻以JSON格式POST到百度語(yǔ)音識(shí)別服務(wù)器,獲得返回結(jié)果
語(yǔ)音格式
格式支持:pcm(不壓縮)、wav(不壓縮,pcm編碼)、amr(壓縮格式)。推薦pcm 采樣率 :16000 固定值。 編碼:16bit 位深的單聲道。
百度服務(wù)端會(huì)將非pcm格式,轉(zhuǎn)為pcm格式,因此使用wav、amr會(huì)有額外的轉(zhuǎn)換耗時(shí)。
保存為pcm格式可以識(shí)別,只是windows自帶播放器識(shí)別不了pcm格式的,所以改用wav格式,畢竟用的模塊是wave?
首先是本地錄音
import wave
from pyaudio import PyAudio, paInt16
framerate = 16000 # 采樣率
num_samples = 2000 # 采樣點(diǎn)
channels = 1 # 聲道
sampwidth = 2 # 采樣寬度2bytes
FILEPATH = 'speech.wav'
def save_wave_file(filepath, data):
wf = wave.open(filepath, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(framerate)
wf.writeframes(b''.join(data))
wf.close()
#錄音
def my_record():
pa = PyAudio()
#打開一個(gè)新的音頻stream
stream = pa.open(format=paInt16, channels=channels,
rate=framerate, input=True, frames_per_buffer=num_samples)
my_buf = [] #存放錄音數(shù)據(jù)
t = time.time()
print('正在錄音...')
while time.time() < t + 4: # 設(shè)置錄音時(shí)間(秒)
#循環(huán)read,每次read 2000frames
string_audio_data = stream.read(num_samples)
my_buf.append(string_audio_data)
print('錄音結(jié)束.')
save_wave_file(FILEPATH, my_buf)
stream.close()
然后是獲取token
import requests
import base64 #百度語(yǔ)音要求對(duì)本地語(yǔ)音二進(jìn)制數(shù)據(jù)進(jìn)行base64編碼
#組裝url獲取token,詳見文檔
base_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"
APIKey = "LZAdqHUGC********mbfKm"
SecretKey = "WYPPwgHu********BU6GM*****"
HOST = base_url % (APIKey, SecretKey)
def getToken(host):
res = requests.post(host)
return res.json()['access_token']
#傳入語(yǔ)音二進(jìn)制數(shù)據(jù),token
#dev_pid為百度語(yǔ)音識(shí)別提供的幾種語(yǔ)言選擇
def speech2text(speech_data, token, dev_pid=1537):
FORMAT = 'wav'
RATE = '16000'
CHANNEL = 1
CUID = '********'
SPEECH = base64.b64encode(speech_data).decode('utf-8')
data = {
'format': FORMAT,
'rate': RATE,
'channel': CHANNEL,
'cuid': CUID,
'len': len(speech_data),
'speech': SPEECH,
'token': token,
'dev_pid':dev_pid
}
url = 'https://vop.baidu.com/server_api'
headers = {'Content-Type': 'application/json'}
# r=requests.post(url,data=json.dumps(data),headers=headers)
print('正在識(shí)別...')
r = requests.post(url, json=data, headers=headers)
Result = r.json()
if 'result' in Result:
return Result['result'][0]
else:
return Result
最后就是對(duì)返回的結(jié)果進(jìn)行匹配,這里使用webbrowser這個(gè)模塊
webbrower.open(url)
完整demo
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date : 2018-12-02 19:04:55
import wave
import requests
import time
import base64
from pyaudio import PyAudio, paInt16
import webbrowser
framerate = 16000 # 采樣率
num_samples = 2000 # 采樣點(diǎn)
channels = 1 # 聲道
sampwidth = 2 # 采樣寬度2bytes
FILEPATH = 'speech.wav'
base_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"
APIKey = "********"
SecretKey = "************"
HOST = base_url % (APIKey, SecretKey)
def getToken(host):
res = requests.post(host)
return res.json()['access_token']
def save_wave_file(filepath, data):
wf = wave.open(filepath, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(framerate)
wf.writeframes(b''.join(data))
wf.close()
def my_record():
pa = PyAudio()
stream = pa.open(format=paInt16, channels=channels,
rate=framerate, input=True, frames_per_buffer=num_samples)
my_buf = []
# count = 0
t = time.time()
print('正在錄音...')
while time.time() < t + 4: # 秒
string_audio_data = stream.read(num_samples)
my_buf.append(string_audio_data)
print('錄音結(jié)束.')
save_wave_file(FILEPATH, my_buf)
stream.close()
def get_audio(file):
with open(file, 'rb') as f:
data = f.read()
return data
def speech2text(speech_data, token, dev_pid=1537):
FORMAT = 'wav'
RATE = '16000'
CHANNEL = 1
CUID = '*******'
SPEECH = base64.b64encode(speech_data).decode('utf-8')
data = {
'format': FORMAT,
'rate': RATE,
'channel': CHANNEL,
'cuid': CUID,
'len': len(speech_data),
'speech': SPEECH,
'token': token,
'dev_pid':dev_pid
}
url = 'https://vop.baidu.com/server_api'
headers = {'Content-Type': 'application/json'}
# r=requests.post(url,data=json.dumps(data),headers=headers)
print('正在識(shí)別...')
r = requests.post(url, json=data, headers=headers)
Result = r.json()
if 'result' in Result:
return Result['result'][0]
else:
return Result
def openbrowser(text):
maps = {
'百度': ['百度', 'baidu'],
'騰訊': ['騰訊', 'tengxun'],
'網(wǎng)易': ['網(wǎng)易', 'wangyi']
}
if text in maps['百度']:
webbrowser.open_new_tab('https://www.baidu.com')
elif text in maps['騰訊']:
webbrowser.open_new_tab('https://www.qq.com')
elif text in maps['網(wǎng)易']:
webbrowser.open_new_tab('https://www.163.com/')
else:
webbrowser.open_new_tab('https://www.baidu.com/s?wd=%s' % text)
if __name__ == '__main__':
flag = 'y'
while flag.lower() == 'y':
print('請(qǐng)輸入數(shù)字選擇語(yǔ)言:')
devpid = input('1536:普通話(簡(jiǎn)單英文),1537:普通話(有標(biāo)點(diǎn)),1737:英語(yǔ),1637:粵語(yǔ),1837:四川話\n')
my_record()
TOKEN = getToken(HOST)
speech = get_audio(FILEPATH)
result = speech2text(speech, TOKEN, int(devpid))
print(result)
if type(result) == str:
openbrowser(result.strip(','))
flag = input('Continue?(y/n):')
經(jīng)測(cè)試,大吼效果更佳?
到此這篇關(guān)于Python調(diào)用百度api實(shí)現(xiàn)語(yǔ)音識(shí)別詳解的文章就介紹到這了,更多相關(guān)Python 語(yǔ)音識(shí)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python實(shí)現(xiàn)簡(jiǎn)單的語(yǔ)音識(shí)別系統(tǒng)
- python3實(shí)現(xiàn)語(yǔ)音轉(zhuǎn)文字(語(yǔ)音識(shí)別)和文字轉(zhuǎn)語(yǔ)音(語(yǔ)音合成)
- python實(shí)現(xiàn)百度語(yǔ)音識(shí)別api
- 使用Python和百度語(yǔ)音識(shí)別生成視頻字幕的實(shí)現(xiàn)
- python版百度語(yǔ)音識(shí)別功能
- 基于Python實(shí)現(xiàn)語(yǔ)音識(shí)別和語(yǔ)音轉(zhuǎn)文字
- 基于python實(shí)現(xiàn)語(yǔ)音錄入識(shí)別代碼實(shí)例
- python語(yǔ)音識(shí)別whisper的使用
相關(guān)文章
Python中基本數(shù)據(jù)類型和常用語(yǔ)法歸納分享
這篇文章主要為大家整理記錄了Python中基本數(shù)據(jù)類型和常用語(yǔ)法的使用,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-04-04
python判斷一個(gè)集合是否包含了另外一個(gè)集合中所有項(xiàng)的方法
這篇文章主要介紹了python判斷一個(gè)集合是否包含了另外一個(gè)集合中所有項(xiàng)的方法,涉及Python集合操作的相關(guān)技巧,需要的朋友可以參考下2015-06-06
Django haystack實(shí)現(xiàn)全文搜索代碼示例
這篇文章主要介紹了Django haystack實(shí)現(xiàn)全文搜索代碼示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11
Python還能這么玩之用Python修改了班花的開機(jī)密碼
今天帶大家學(xué)習(xí)如何用Python修改開機(jī)密碼,文中有非常詳細(xì)的代碼示例,喜歡惡作劇的小伙伴可以看一下,不過(guò)不要亂用哦,需要的朋友可以參考下2021-06-06
在Python中利用Pandas庫(kù)處理大數(shù)據(jù)的簡(jiǎn)單介紹
這篇文章簡(jiǎn)單介紹了在Python中利用Pandas處理大數(shù)據(jù)的過(guò)程,Pandas庫(kù)的使用能夠很好地展現(xiàn)數(shù)據(jù)結(jié)構(gòu),是近來(lái)Python項(xiàng)目中經(jīng)常被使用使用的熱門技術(shù),需要的朋友可以參考下2015-04-04

