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

Python类Alexa语音助手代码调试及功能完善请求

类Alexa语音助手调试与修复方案

一、错误分析与逐个解决

1. 缺失依赖包错误

  • ModuleNotFoundError: No module named 'speech_recognition':安装语音识别库即可解决
    执行命令:pip install SpeechRecognition
  • ModuleNotFoundError: No module named 'pyaudio':PyAudio是麦克风输入的核心依赖,分平台安装:
    • Windows:先装pip install pipwin,再执行pipwin install pyaudio
    • Linux:先运行sudo apt-get install portaudio19-dev,再执行pip install pyaudio
    • macOS:先运行brew install portaudio,再执行pip install pyaudio
  • ImportError: cannot import name 'speak' from 'text_to_speech':text_to_speech库没有内置speak函数,要么自己实现音频播放逻辑,要么改用更易用的pyttsx3库直接输出语音(推荐后者)

2. 函数未定义错误

代码里多次调用speak()但从没定义过这个函数。如果继续用text_to_speech.save生成音频文件,可结合pygame实现播放;更高效的方式是用pyttsx3直接生成语音输出,不用临时文件。

3. 文件格式错误

ValueError: reply is in a '' format, it should be in a '.mp3' format.:save函数要求文件名必须带.mp3后缀,所有调用save的地方要确保file参数是完整的MP3文件名(比如file="reply.mp3",不能只写file="reply")。

4. 逻辑与交互错误

  • record_audio(speak("xxx")):错误地把speak的返回值当参数传入,应该先执行语音提示,再传字符串,比如:
    speak("what do you want to open")
    launch = record_audio("what do you want to open")
    
  • subprocess.call(launch + '.exe'):直接拼接字符串有安全风险,还没处理程序不存在的情况,要改成列表形式并加异常捕获
  • 音乐播放部分用input()依赖键盘输入,不符合语音助手的定位,改成语音识别控制更合理

二、修正后的完整代码

以下代码改用pyttsx3实现语音输出(无需生成临时MP3,响应更快),修复所有错误并优化逻辑:

import speech_recognition as sr
from time import ctime as t
import subprocess
import webbrowser
from translate import Translator
import random
from pygame import mixer
import pyttsx3

# 初始化语音引擎
engine = pyttsx3.init()
r = sr.Recognizer()

def speak(text):
    """语音输出函数"""
    engine.say(text)
    engine.runAndWait()

def record_audio(ask=False):
    """录制音频并转为文字"""
    with sr.Microphone() as source:
        # 降噪处理,提升识别准确率
        r.adjust_for_ambient_noise(source, duration=0.5)
        if ask:
            print(ask)
            speak(ask)
        audio = r.listen(source)
        voice_data = ''
        try:
            voice_data = r.recognize_google(audio, language="en-us")
            print(f"You said: {voice_data}")
        except sr.UnknownValueError:
            speak("Sorry, I don't get that")
        except sr.RequestError:
            speak("Sorry, the speech service is down")
        return voice_data.lower()

def respond(voice_data):
    """根据语音指令执行对应操作"""
    if 'what is your name' in voice_data:
        speak("My name is Alex")
    if 'what time is it' in voice_data:
        speak(f"The current time is {t()}")
    if 'search' in voice_data:
        search_query = record_audio('What do you want to search for?')
        if search_query:
            url = f'https://google.com/search?q={search_query}'
            webbrowser.get().open(url)
            speak(f"Here's what I found for {search_query}")
    if 'open' in voice_data:
        app_name = record_audio('What do you want to open?')
        if app_name:
            try:
                # Windows下打开应用,其他系统可自行调整
                subprocess.call([f"{app_name}.exe"], shell=True)
                speak(f"Opening {app_name}")
            except FileNotFoundError:
                speak(f"Sorry, I can't find {app_name}")
    if 'translate' in voice_data:
        to_lang = record_audio('Enter the language code: hi for Hindi, en for English, fr for French, de for German')
        if to_lang:
            text_to_translate = record_audio('What do you want to translate?')
            if text_to_translate:
                try:
                    translator = Translator(to_lang=to_lang)
                    translation = translator.translate(text_to_translate)
                    speak(f"The translation is: {translation}")
                except Exception as e:
                    speak("Sorry, translation failed")
    if 'i am bored' in voice_data:
        choice = record_audio('Should I tell a joke or play music?')
        if 'joke' in choice:
            joke = random.choice([
                "I went to the doctor the other day and said: 'Have you got anything for wind?' So he gave me a kite.",
                "Why do we tell actors to break a leg? Because every play has a cast.",
                "Why don’t scientists trust atoms? Because they make up everything."
            ])
            speak(joke)
        elif 'music' in choice:
            try:
                mixer.init()
                mixer.music.load("song.mp3")
                mixer.music.set_volume(0.7)
                mixer.music.play()
                speak("Playing music. Say 'pause' to pause, 'resume' to resume, 'stop' to exit.")
                while mixer.music.get_busy():
                    control_cmd = record_audio()
                    if 'pause' in control_cmd:
                        mixer.music.pause()
                        speak("Paused")
                    elif 'resume' in control_cmd:
                        mixer.music.unpause()
                        speak("Resumed")
                    elif 'stop' in control_cmd:
                        mixer.music.stop()
                        speak("Stopped playing")
                        break
            except FileNotFoundError:
                speak("Sorry, the song file is missing")

# 主循环
while True:
    speak("How can I help you?")
    voice_data = record_audio()
    if voice_data:
        respond(voice_data)

三、额外优化说明

  • 添加adjust_for_ambient_noise降噪处理,提升语音识别准确率
  • 改用pyttsx3直接输出语音,避免生成临时MP3文件,响应更流畅
  • 增加异常捕获,处理文件缺失、命令执行失败等场景
  • 音乐播放改为语音控制,贴合语音助手的交互逻辑
  • 打印用户语音内容,方便调试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:19:57