Python-懒人必备-语音小助手
生活随笔
收集整理的這篇文章主要介紹了
Python-懒人必备-语音小助手
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
又是復(fù)習(xí)學(xué)習(xí)熟悉語法的一天。
import speech_recognition as sr from os import path from aip import AipSpeech import sys, os from pynput.keyboard import Controller,Key,Listener from tkinter import * import multiprocessing as mp AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "test.wav") audio_order=path.join(path.dirname(path.realpath(__file__)), "order.txt")list=[]#將命令添加至列表 read_dict={}#本地txt命令轉(zhuǎn)換為字典 """ 你的 APPID AK SK """ APP_ID = '*******' API_KEY = '*******' SECRET_KEY = '*******' client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)#電腦麥克風(fēng)錄音 def reco():r = sr.Recognizer()try:with sr.Microphone(sample_rate=16000) as source:print("請朗讀語音命令")audio = r.listen(source,timeout=3)with open(AUDIO_FILE,'wb') as f:f.write(audio.get_wav_data())except:print('暫無錄音內(nèi)容')#百度語音識(shí)別 def asr(filePath):try:with open(filePath, 'rb') as fp:music=fp.read()result=client.asr(music, 'wav', 16000, {'dev_pid': 1536,})list.append(result['result'][0])return result['result'][0]except:print('無法識(shí)別口令有誤')list.append(1)#獲取指令 def get_order():fileRead=open(audio_order,'r',encoding='utf-8')lines=fileRead.readlines()for line in lines:line_list=line.split(',')#每行按逗號(hào)分隔成列表id=line_list[0]#取到idpath=line_list[1]#取到nameread_dict[id]=path#此處關(guān)鍵產(chǎn)生鍵值對,其中key是id#檢測按鍵 def on_press(key):try:if key.char=='c':reco()if asr(AUDIO_FILE) in read_dict:print('正在打開')os.system(read_dict.get(list[0]))del list[0]os.remove(AUDIO_FILE)print('打開完畢')else:print('錯(cuò)誤指令重新聆聽')del list[0]except AttributeError:print("正在按壓:",format(key))# 開始監(jiān)聽 def start_listen():with Listener(on_press=on_press) as listener:get_order()print('等待指令')listener.join() #進(jìn)程處理 def process():global pp = mp.Process(target=start_listen)p.start()if __name__ == "__main__":app=Tk()app.title('語音小助手')app.geometry('250x150')label=Label(app,text='C鍵喚醒,自動(dòng)聆聽').pack()button_run=Button(app,text='開啟聆聽',command=process,width=10,height=10).pack()app.mainloop()print('退出')p.terminate()#進(jìn)程終止
order.txt(example)
實(shí)現(xiàn)功能:c鍵喚起,聆聽3秒,可以實(shí)現(xiàn)在任何界面下的喚醒,無彈窗,指令可以寫在當(dāng)前文件夾的order.txt里面,英文逗號(hào)隔開,當(dāng)然也可以實(shí)現(xiàn)一些其他功能而非打開應(yīng)用。
總結(jié)
以上是生活随笔為你收集整理的Python-懒人必备-语音小助手的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 快速清除字符串边上的空格
- 下一篇: Ubuntu+Tesla M40上Ope