使用 Python 实现:对着电脑吼一声,自动打开浏览器中的默认网站。

Python 练习册,每天一个小程序

原题:
第 0025 题: 使用 Python 实现:对着电脑吼一声,自动打开浏览器中的默认网站。

例如,对着笔记本电脑吼一声“百度”,浏览器自动打开百度首页。

参考思路:
1:获取电脑录音–>WAV文件 python record wav

2:录音文件–>文本

3:文本–>电脑命令

代码如下:

# -*- coding: utf-8 -*-
import wave, pyaudio
import webbrowser
'''
百度语音识别SDK
'''
# 引入Speech SDK
from aip import AipSpeech
# 定义常量
APP_ID = '你的 App ID'
API_KEY = '你的 API Key'
SECRET_KEY = '你的 Secret Key'

# 初始化AipSpeech对象
aipSpeech = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

CHUNK = 1024
FORMAT = pyaudio.paInt16
RATE = 8000
CHANNELS = 1
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

def record_wave():
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)
    print("* recording")
    frames = []
    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)

    print("* done recording")

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

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

def browser_open_text(text):
    str = (text[0])[:-1]
    print(str)
    if str is None:
        return
    elif 'baidu' == str:
        webbrowser.open_new_tab("baidu.com")
    else:
        webbrowser.open_new_tab("doubiiot.cn")

def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

if __name__ == "__main__":
    record_wave()
    res = aipSpeech.asr(get_file_content("output.wav"), 'wav', 8000, { 'lan': 'zh',})
    while res['err_no'] != 0:
        print("Please speak again")
        record_wave()
    if 'result' in res:
        text = res['result']
        browser_open_text(text)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值