Python 練習(xí)冊 25題 (api)

第 0025 題: 使用 Python 實(shí)現(xiàn):對著電腦吼一聲,自動(dòng)打開瀏覽器中的默認(rèn)網(wǎng)站。

例如,對著筆記本電腦吼一聲“百度”,瀏覽器自動(dòng)打開百度首頁。

關(guān)鍵字:Speech to Text
參考思路:
1:獲取電腦錄音-->WAV文件 python record wav

2:錄音文件-->文本

STT: Speech to Text

STT API Google API
3:文本-->電腦命令

from tkinter import *
import pyaudio
import wave
import requests
import json
import pycurl
from io import BytesIO
import os


CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 8000
RECORD_SECONDS = 5


# 錄音保存
def record_wave():
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)

    print("正在錄音...")
    frames = []

    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)

    print("錄音結(jié)束")

    stream.stop_stream()
    stream.close()
    p.terminate()

    wf = wave.open('output.wav', 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()


# 界面
def button():
    root = Tk()

    label = Label(root)
    label['text'] = '點(diǎn)擊開始,開始錄音'
    label.pack()

    button1 = Button(root)
    button1['text'] = '開始'
    button1['command'] = record_wave
    button1["fg"] = "red"
    button1.pack({"side": "left"})

    button2 = Button(root)
    button2['text'] = '退出'
    button2['command'] = root.quit
    button2["fg"] = "blue"
    button2.pack({"side": "left"})

    root.mainloop()
    root.destroy()


def get_token():
    apiId = '9550153'
    apiKey = 't2ePzNA79W4dOEVkhmDCB7al'
    secretKey = '248a85ff8c633684760a0b53bfebe2ef'

    url = 'https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id='\
          + apiKey + '&client_secret=' + secretKey + '&'
    data = requests.post(url)
    token = json.loads(data.content).get('access_token')
    return token


def post_voice(token):
    fp = wave.open('output.wav', 'rb')
    nf = fp.getnframes()
    f_len = nf * 2
    audio_data = fp.readframes(nf)

    cuid = "778617402"
    srv_url = 'http://vop.baidu.com/server_api' + '?cuid=' + cuid + '&token=' + token
    http_header = [
        'Content-Type: audio/pcm; rate=8000',
        'Content-Length: %d' % f_len
    ]

    buffer = BytesIO()
    c = pycurl.Curl()
    c.setopt(pycurl.URL, str(srv_url))
    c.setopt(c.HTTPHEADER, http_header)
    c.setopt(c.POST, 1)
    c.setopt(c.CONNECTTIMEOUT, 30)
    c.setopt(c.TIMEOUT, 30)
    c.setopt(c.POSTFIELDS, audio_data)
    c.setopt(c.POSTFIELDSIZE, f_len)

    c.setopt(c.WRITEDATA, buffer)

    c.perform()
    c.close()
    resp = buffer.getvalue().decode('utf-8')
    data = json.loads(resp)
    result = data.get('result')[0]
    return result


def run():
    # 運(yùn)行用戶界面,錄音并保存文件
    button()
    # 獲得token
    token = get_token()
    # 提交聲音文件
    result = post_voice(token=token)
    return result

result = run()
print(result)
if '瀏覽器' in result:
    os.startfile(r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')





最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前言 Python的創(chuàng)始人為Guido van Rossum。1989年圣誕節(jié)期間,在阿姆斯特丹,Guido為了打...
    依依玖玥閱讀 3,705評論 6 37
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,177評論 4 61
  • Swift版本點(diǎn)擊這里歡迎加入QQ群交流: 594119878最新更新日期:18-09-17 About A cu...
    ylgwhyh閱讀 26,009評論 7 249
  • 第十六章 我只是 一顆多情的種子 前世今生 被風(fēng)吹在你所遺忘的角落 渺小而卑微 自生自滅在春去冬來的日夜 彼岸的花...
    碧海青天2017閱讀 551評論 1 1
  • 由于CPU和內(nèi)存的速度遠(yuǎn)遠(yuǎn)高于外設(shè)的速度,所以,在IO編程中,就存在速度嚴(yán)重不匹配的問題。舉個(gè)例子來說,比如要把1...
    Asa_Guo閱讀 3,801評論 0 4

友情鏈接更多精彩內(nèi)容