Skip to content

Commit 98bc77d

Browse files
committed
0025: 语音打开浏览器搜索引擎
1 parent 49c7aa4 commit 98bc77d

3 files changed

Lines changed: 194 additions & 1 deletion

File tree

xyjxyf/0025/voice_open_browser.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# encoding = utf-8
2+
3+
# use pyAudio
4+
# brew install portaudio
5+
# pip install pyaudio
6+
7+
import wave, pyaudio
8+
from datetime import datetime
9+
from tools import dxbaiduaudio
10+
import webbrowser
11+
12+
CHUNK = 1024
13+
FORMAT = pyaudio.paInt16
14+
RATE = 8000
15+
CHANNELS = 1
16+
RECORD_SECONDS = 5
17+
18+
def record_wave(to_dir=None):
19+
if to_dir is None:
20+
to_dir = "./"
21+
22+
pa = pyaudio.PyAudio()
23+
stream = pa.open(format = FORMAT,
24+
channels = CHANNELS,
25+
rate = RATE,
26+
input = True,
27+
frames_per_buffer = CHUNK)
28+
29+
print("* recording")
30+
31+
save_buffer = []
32+
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
33+
audio_data = stream.read(CHUNK)
34+
save_buffer.append(audio_data)
35+
36+
print("* done recording")
37+
38+
# stop
39+
stream.stop_stream()
40+
stream.close()
41+
pa.terminate()
42+
43+
# wav path
44+
file_name = datetime.now().strftime("%Y-%m-%d_%H_%M_%S")+".wav"
45+
if to_dir.endswith('/'):
46+
file_path = to_dir + file_name
47+
else:
48+
file_path = to_dir + "/" + file_name
49+
50+
# save file
51+
wf = wave.open(file_path, 'wb')
52+
wf.setnchannels(CHANNELS)
53+
wf.setsampwidth(pa.get_sample_size(FORMAT))
54+
wf.setframerate(RATE)
55+
# join 前的类型
56+
wf.writeframes(b''.join(save_buffer))
57+
wf.close()
58+
59+
return file_path
60+
61+
def browser_open_text(text):
62+
if text is None:
63+
return
64+
65+
url = "http://www.baidu.com"
66+
if text.startswith("谷歌") or text.startswith("google"):
67+
url = "http://www.google.com"
68+
elif text.startswith("必应") or text.startswith("bing"):
69+
url = "http://cn.bing.com"
70+
71+
webbrowser.open_new_tab(url)
72+
73+
if __name__ == "__main__":
74+
to_dir = "./"
75+
file_path = record_wave(to_dir)
76+
77+
text = dxbaiduaudio.wav_to_text(file_path)
78+
browser_open_text(text)

xyjxyf/show_me_the_code.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -516,7 +516,7 @@ def encrypt_password(password, salt=None):
516516

517517

518518
# 第 0025 题: 使用 Python 实现:对着电脑吼一声,自动打开浏览器中的默认网站
519-
519+
# 在文件夹0025中实现
520520

521521

522522
if __name__ == "__main__":

xyjxyf/tools/dxbaiduaudio.py

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# encoing = utf-8
2+
3+
from urllib import request
4+
import json, base64, uuid, os
5+
import wave
6+
import pycurl
7+
import io
8+
9+
bda_app_id = "7972313"
10+
bda_api_key = "ZrjLfF5Rh7pOL66gaOmDGnXn"
11+
bda_secret_key = "16bac9645093ca2632ebb81015ff7544"
12+
13+
bda_access_token = ""
14+
bda_expires_in = ""
15+
ret_text = ""
16+
17+
def get_mac_address():
18+
return uuid.UUID(int=uuid.getnode()).hex[-12:]
19+
20+
def get_access_token():
21+
url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=ZrjLfF5Rh7pOL66gaOmDGnXn&client_secret=16bac9645093ca2632ebb81015ff7544"
22+
23+
req = request.Request(url, method="POST")
24+
resp = request.urlopen(req)
25+
data = resp.read().decode('utf-8')
26+
json_data = json.loads(data)
27+
28+
global bda_access_token
29+
bda_access_token = json_data['access_token']
30+
31+
return bda_access_token
32+
33+
CHUNK = 1024
34+
def get_wav_data(wav_path):
35+
if wav_path is None or len(wav_path) == 0:
36+
return None
37+
38+
fp = wave.open(wav_path, 'rb')
39+
nf = fp.getnframes()
40+
f_len = nf * 2
41+
audio_data = fp.readframes(nf)
42+
43+
return audio_data, f_len
44+
45+
def dump_res(buf):
46+
resp_json = json.loads(buf.decode('utf-8'))
47+
ret = resp_json['result']
48+
49+
global ret_text
50+
ret_text = ret[0]
51+
52+
print(buf)
53+
54+
def wav_to_text(wav_path):
55+
if wav_path is None or len(wav_path) == 0:
56+
return None
57+
58+
if len(bda_access_token) == 0:
59+
get_access_token()
60+
if len(bda_access_token) == 0:
61+
return None
62+
63+
data, f_len = get_wav_data(wav_path)
64+
65+
url = 'http://vop.baidu.com/server_api?cuid=' + get_mac_address() + '&token=' + bda_access_token
66+
http_header = [
67+
'Content-Type: audio/pcm; rate=8000',
68+
'Content-Length: %d' % f_len
69+
]
70+
71+
c = pycurl.Curl()
72+
c.setopt(pycurl.URL, str(url)) #curl doesn't support unicode
73+
#c.setopt(c.RETURNTRANSFER, 1)
74+
c.setopt(c.HTTPHEADER, http_header) #must be list, not dict
75+
c.setopt(c.POST, 1)
76+
c.setopt(c.CONNECTTIMEOUT, 30)
77+
c.setopt(c.TIMEOUT, 30)
78+
c.setopt(c.WRITEFUNCTION, dump_res)
79+
c.setopt(c.POSTFIELDS, data)
80+
c.setopt(c.POSTFIELDSIZE, f_len)
81+
c.perform() #pycurl.perform() has no return val
82+
83+
return ret_text
84+
85+
86+
# def wav_to_text(wav_path):
87+
# if wav_path is None or len(wav_path) == 0:
88+
# return None
89+
#
90+
# wav_data = get_wav_data(wav_path)
91+
# if wav_data is None:
92+
# return None
93+
#
94+
# if len(bda_access_token) == 0:
95+
# get_access_token()
96+
#
97+
# wav_base64 = base64.b64decode(wav_data)
98+
# print("%s", wav_base64)
99+
# # unicode( wav_base64, errors='ignore')
100+
# wav_len = len(wav_data)
101+
# data_dic = {'format':'wav', 'rate':8000, 'channel':1,
102+
# 'cuid':get_mac_address(), 'token':bda_access_token,
103+
# b'speech':wav_base64, 'len':wav_len}
104+
# json_data = json.dumps(data_dic).encode('utf-8')
105+
# json_len = len(json_data)
106+
#
107+
# req = request.Request('http://vop.baidu.com/server_api')
108+
# req.add_header('Content-Type', "application/json")
109+
# req.add_header("Content-Length", json_len)
110+
# resp = request.urlopen(req, data=json_data)
111+
#
112+
# resp_data = resp.read().decode('utf-8')
113+
# resp_json = json.loads(resp_data)
114+
#
115+
# return resp_json['result']

0 commit comments

Comments
 (0)