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

如何解决选择Google时触发的UnboundLocalError: rYouTube未赋值引用问题?

问题分析与修复方案

咱先一步步拆解你的问题,搞定那个UnboundLocalError,顺便修正代码里的其他明显问题。

核心错误原因:UnboundLocalError

这个错误通常是因为Python把rYouTube判定为局部变量,但你在给它赋值前就尝试引用了。结合你贴的代码,可能的场景有两种:

  1. 你的代码被包裹在函数内部,但rYouTube只在YouTube分支里定义,走Google分支时函数内未初始化该变量;
  2. 你在Google分支的代码里不小心笔误,把rGoogle写成了rYouTube,导致Python认为你要给局部变量rYouTube赋值,但赋值前就有地方引用了它。

其他代码问题(必须修正)

除了核心错误,你的代码还有几个明显的bug:

  • 未定义的recognized变量:你用if "Google" in recognized:判断,但代码里从来没给这个变量赋值;
  • Google搜索部分的变量错误:
    • 拼写错误:FinalSearchGooleAudio应该是FinalSearchGoogleAudio;
    • 错误引用YouTube的音频变量:SearchGoogle.recognize_google(YTSearchAudio)里的YTSearchAudio要改成Google分支的GoogleSearchAudio;
    • 搜索链接错误:Google搜索应该用https://www.google.com/search?q=而非YouTube的链接;
  • 未处理识别失败的场景:如果语音识别失败,后续if "yes" in ...会因为变量未定义报错。

修正后的完整代码

import speech_recognition as sr
import time
import webbrowser

# 第一步:让用户选择YouTube或Google
print("Choose YouTube or Google:")
rSelector = sr.Recognizer()
with sr.Microphone() as source:
    rSelector.adjust_for_ambient_noise(source)
    selector_audio = rSelector.listen(source)

recognized = ""
try:
    recognized = rSelector.recognize_google(selector_audio).lower()
    print(f"You chose: {recognized}")
except sr.UnknownValueError:
    print("Google Speech Recognition could not understand audio")
    exit()
except sr.RequestError as e:
    print(f"Could not request results from Google Speech Recognition service; {e}")
    exit()

# YOUTUBE DIRECT SEARCH-------------------------------------
if "youtube" in recognized:
    print("Would you like to Direct Search?")
    rYouTube = sr.Recognizer()
    with sr.Microphone() as source:
        rYouTube.adjust_for_ambient_noise(source)
        YTaudio = rYouTube.listen(source)
    print("LOADING...")
    time.sleep(1)
    DirectYTRecognized = ""
    try:
        DirectYTRecognized = rYouTube.recognize_google(YTaudio).lower()
        print(DirectYTRecognized)
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print(f"Could not request results from Google Speech Recognition service; {e}")
    
    if "yes" in DirectYTRecognized:
        print("What do you want to watch?")
        SearchYouTube = sr.Recognizer()
        with sr.Microphone() as source:
            SearchYouTube.adjust_for_ambient_noise(source)
            YTSearchAudio = SearchYouTube.listen(source)
        print("LOADING...")
        time.sleep(1)
        try:
            FinalSearchYTAudio = SearchYouTube.recognize_google(YTSearchAudio)
            print(FinalSearchYTAudio)
            DirectYT = f"https://youtube.com/results?search_query={FinalSearchYTAudio}"
            webbrowser.open_new(DirectYT)
        except sr.UnknownValueError:
            print("Google Speech Recognition could not understand audio")
        except sr.RequestError as e:
            print(f"Could not request results from Google Speech Recognition service; {e}")

# GOOGLE DIRECT SEARCH---------------------------------------
elif "google" in recognized:
    print("Would you like to Direct Search?")
    rGoogle = sr.Recognizer()
    with sr.Microphone() as source:
        rGoogle.adjust_for_ambient_noise(source)
        GoogleAudio = rGoogle.listen(source)
    print("LOADING...")
    time.sleep(1)
    DirectGoogleRecognized = ""
    try:
        DirectGoogleRecognized = rGoogle.recognize_google(GoogleAudio).lower()
        print(DirectGoogleRecognized)
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print(f"Could not request results from Google Speech Recognition service; {e}")
    
    if "yes" in DirectGoogleRecognized:
        print("What do you want to look up?")
        SearchGoogle = sr.Recognizer()
        with sr.Microphone() as source:
            SearchGoogle.adjust_for_ambient_noise(source)
            GoogleSearchAudio = SearchGoogle.listen(source)
        print("LOADING...")
        time.sleep(1)
        try:
            FinalSearchGoogleAudio = SearchGoogle.recognize_google(GoogleSearchAudio)
            print(FinalSearchGoogleAudio)
            DirectGoogle = f"https://www.google.com/search?q={FinalSearchGoogleAudio}"
            webbrowser.open_new(DirectGoogle)
        except sr.UnknownValueError:
            print("Google Speech Recognition could not understand audio")
        except sr.RequestError as e:
            print(f"Could not request results from Google Speech Recognition service; {e}")
else:
    print("Sorry, I didn't catch that. Please choose YouTube or Google.")

关键修正点说明

  1. 补全初始选择逻辑:添加了用户选择YouTube/Google的语音识别步骤,定义了recognized变量;
  2. 避免变量未定义:在每个识别步骤前初始化结果变量(比如DirectYTRecognized = ""),防止识别失败后后续判断报错;
  3. 修正变量引用与拼写:修复了Google分支的音频变量引用错误和拼写错误;
  4. 优化分支判断:用if...elif...else替代独立的if,避免同时触发两个分支;
  5. 全局/局部变量处理:如果你的代码是放在函数内部的,建议在函数开头初始化所有可能用到的识别器变量(比如rYouTube = None),或者用global声明全局变量,彻底解决UnboundLocalError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:39:53