最近在學(xué)習(xí)python,做一些python練習(xí)題
github上幾年前的練習(xí)題
有一題是這樣的:
使用 Python 實現(xiàn):對著電腦吼一聲,自動打開瀏覽器中的默認網(wǎng)站。
例如,對著筆記本電腦吼一聲“百度”,瀏覽器自動打開百度首頁。
然后開始search相應(yīng)的功能需要的模塊(windows10),理一下思路:
所需模塊:
為什么要用百度語音識別api呢?因為免費試用。。
選擇2.
語音格式
格式支持:pcm(不壓縮)、wav(不壓縮,pcm編碼)、amr(壓縮格式)。推薦pcm 采樣率 :16000 固定值。 編碼:16bit 位深的單聲道。
百度服務(wù)端會將非pcm格式,轉(zhuǎn)為pcm格式,因此使用wav、amr會有額外的轉(zhuǎn)換耗時。
保存為pcm格式可以識別,只是windows自帶播放器識別不了pcm格式的,所以改用wav格式,畢竟用的模塊是wave
?
首先是本地錄音
import wavefrom pyaudio import PyAudio, paInt16framerate = 16000 # 采樣率num_samples = 2000 # 采樣點channels = 1 # 聲道sampwidth = 2 # 采樣寬度2bytesFILEPATH = '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() #打開一個新的音頻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è)置錄音時間(秒) #循環(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 requestsimport base64 #百度語音要求對本地語音二進制數(shù)據(jù)進行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']#傳入語音二進制數(shù)據(jù),token#dev_pid為百度語音識別提供的幾種語言選擇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('正在識別...') r = requests.post(url, json=data, headers=headers) Result = r.json() if 'result' in Result: return Result['result'][0] else: return Result
最后就是對返回的結(jié)果進行匹配,這里使用webbrowser
這個模塊
webbrower.open(url)
完整demo
#!/usr/bin/env python# -*- coding: utf-8 -*-# Date : 2018-12-02 19:04:55import waveimport requestsimport timeimport base64from pyaudio import PyAudio, paInt16import webbrowserframerate = 16000 # 采樣率num_samples = 2000 # 采樣點channels = 1 # 聲道sampwidth = 2 # 采樣寬度2bytesFILEPATH = '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 datadef 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('正在識別...') r = requests.post(url, json=data, headers=headers) Result = r.json() if 'result' in Result: return Result['result'][0] else: return Resultdef 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('請輸入數(shù)字選擇語言:') devpid = input('1536:普通話(簡單英文),1537:普通話(有標點),1737:英語,1637:粵語,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)測試,大吼效果更佳