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

如何实现Python语音助手的命令式休眠与唤醒功能(不终止脚本)

Solution: Add Sleep/Wake Toggle to Your Python Voice Assistant

Got it, let's get this sleep/wake functionality working for your Jarvis assistant! The core idea is to add a state flag that tracks whether the assistant is active (listening for all commands) or asleep (only listening for the "wake up" trigger). Here's how to implement it step by step:

Key Changes Explained

  • Add a boolean variable is_active to track the assistant's state (starts as True since we want it active initially)
  • Prioritize handling the "go to sleep" and "wake up" commands before processing other tasks
  • When asleep, skip all regular command processing until the "wake up" keyword is detected

Updated Full Code

import speech_recognition as sr
import wikipedia
import datetime
import pywhatkit
import webbrowser as wb
import os
from requests import get
import wolframalpha
import pyttsx3  # Fixed: Moved import to top for clarity

# WolframAlpha setup
try:
    app = wolframalpha.Client('')  # Don't forget to add your API key here!
except Exception:
    print("Some features are not working")

# Text-to-speech setup
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[4].id)  # Changing index changes voices
engine.runAndWait()

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

def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        # Only speak "Listening..." if active (optional tweak for better UX)
        global is_active
        if is_active:
            speak("Listening...")
        audio = r.listen(source)
    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='en-in')
        print(f"user said: {query}\n")
        return query.lower()  # Convert to lowercase once for easier matching
    except Exception as e:
        print("Sorry i didn't catch that...")
        return ""

def wish():
    hour = datetime.datetime.now().hour
    if hour >= 6 and hour < 12:
        speak("Good Morning Sir!")
    elif hour >= 12 and hour < 18:
        speak("Good after noon Sir!")
    elif hour >= 18 and hour < 24:
        speak("Good evening Sir!")
    speak("I am jarvis your personal assistant")

def time():
    Time = datetime.datetime.now().strftime("%I:%M:%S")
    speak(Time)

def date():
    year = int(datetime.datetime.now().year)
    month = int(datetime.datetime.now().month)
    date = int(datetime.datetime.now().day)
    speak(date)
    speak(month)
    speak(year)

if __name__ == "__main__":
    wish()
    is_active = True  # State flag to track if assistant is active
    
    while True:
        query = takeCommand()
        
        # Handle sleep/wake commands first (always listen for these!)
        if 'go to sleep' in query:
            speak("Okay, I'm going to sleep. Say 'wake up' to activate me again.")
            is_active = False
            continue
        elif 'wake up' in query:
            if not is_active:
                speak("I'm awake now! How can I help you?")
                is_active = True
            else:
                speak("I'm already awake sir!")
            continue
        
        # Skip regular commands if assistant is asleep
        if not is_active:
            continue
        
        # Process regular commands when active
        if 'according to wikipedia' in query:
            speak('Searching wikipedia...')
            query = query.replace("wikipedia", "")
            try:
                results = wikipedia.summary(query, sentences=3)
                speak(results)
            except wikipedia.exceptions.PageError:
                speak("I couldn't find that page on Wikipedia.")
        elif 'numbers' in query or 'science' in query:
            try:
                res = app.query(query)
                speak(next(res.results).text)
            except:
                print("Internet connection error ")
                speak("Sorry, I can't process that right now. Check your internet connection.")
        elif 'what is your name' in query:
            speak("My name is Jarvis, I am your personal assistant")
        # Add more command handlers here as needed

Extra Tweaks I Added

  1. Moved pyttsx3 import to the top for better code organization
  2. Made takeCommand() return lowercase queries to simplify keyword matching
  3. Updated the WolframAlpha handler to combine "numbers" and "science" commands (since they use the same logic)
  4. Added a user-friendly message when Wikipedia can't find a page
  5. Made the "Listening..." prompt only play when the assistant is active (so it doesn't keep speaking while asleep)

Now when you say "go to sleep", Jarvis will stop processing all commands except "wake up"—and the script keeps running in the background until you wake it up again!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 03:47:37