You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发类Jarvis语音助手时Chrome语音搜索功能实现故障求助

类Jarvis助手Chrome搜索功能修复方案

首先明确代码存在的4个核心问题:

  • Chrome启动路径配置错误:原路径仅写到Application目录,未指定chrome.exe执行文件,同时Windows路径的反斜杠属于Python转义字符,未做处理会导致路径识别失效
  • 搜索逻辑不符合预期:直接给搜索词拼接.com仅能打开对应域名站点,无法实现通用关键词搜索
  • 语音识别参数格式错误:谷歌识别接口的语言参数应为en-US,原代码写为en.US会导致识别准确率下降甚至报错
  • 无异常捕获逻辑:浏览器调用、语音识别失败时没有兜底处理,程序会直接抛出异常终止

修复后代码

import pyttsx3
import speech_recognition as sr
import webbrowser as wb
from urllib.parse import quote

engine = pyttsx3.init()

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

def wishme():
    speak("Welcome back Summer.")
    speak("Jarvis at your service. How may I help you today?")

def TakeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)

    try:
        print("Recognizing...")
        # 修正语言参数格式
        query = r.recognize_google(audio, language='en-US')
        print(query)

    except Exception as e:
        print(e)
        print("Say that again please...")
        return "None"

    return query

if __name__ == "__main__":
    # 提前注册Chrome路径,使用原始字符串避免转义问题,补充chrome.exe
    chromepath = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
    wb.register('chrome', None, wb.BackgroundBrowser(chromepath))
    
    wishme()

    while True:
        query = TakeCommand().lower()

        if 'search in chrome' in query:
            speak("What should I search?")
            search = TakeCommand().lower()
            if search != "none":
                try:
                    # 拼接谷歌搜索地址,对搜索词做url编码避免特殊字符报错
                    search_url = f'https://www.google.com/search?q={quote(search)}'
                    wb.get('chrome').open_new_tab(search_url)
                    speak(f"Searching {search} in Chrome")
                except Exception as e:
                    print(f"Open Chrome failed: {e}")
                    speak("Sorry, I can't open Chrome right now")

补充说明

如果你的Chrome安装在非默认路径,将chromepath变量的值替换为你本地chrome.exe的实际路径即可。如果需要用其他搜索引擎,只需要把search_url的拼接规则替换为对应搜索引擎的搜索参数格式即可。

内容的提问来源于stack exchange,提问作者CapnNebs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 13:57:04