最近在學(xué)習(xí)python,做一些python練習(xí)題
github上幾年前的練習(xí)題
有一題是這樣的:
使用 Python 實(shí)現(xiàn):對(duì)著電腦吼一聲,自動(dòng)打開(kāi)瀏覽器中的默認(rèn)網(wǎng)站。
例如,對(duì)著筆記本電腦吼一聲“百度”,瀏覽器自動(dòng)打開(kāi)百度首頁(yè)。
然后開(kāi)始search相應(yīng)的功能需要的模塊(windows10),理一下思路:
- 本地錄音
- 上傳錄音,獲得返回結(jié)果
- 組一個(gè)map,根據(jù)結(jié)果打開(kāi)相應(yīng)的網(wǎng)頁(yè)
所需模塊:
- PyAudio:錄音接口
- wave:打開(kāi)錄音文件并設(shè)置音頻參數(shù)
- requests:GET/POST
為什么要用百度語(yǔ)音識(shí)別api呢?因?yàn)槊赓M(fèi)試用。。
不多說(shuō),登錄百度云,創(chuàng)建應(yīng)用
查看文檔REST API文檔
文檔寫(xiě)的蠻詳細(xì)的,簡(jiǎn)單概括就是
- 可以下載使用SDK
- 不需要下載使用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()
#打開(kāi)一個(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,詳見(jiàn)文檔
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è)試,大吼效果更佳
|