如何开发类似Alexa、Cortana的Python关键词唤醒触发函数应用?
Got it, building a voice-activated assistant that listens for a wake word and triggers specific functions is totally achievable in Python. Let’s break this down into actionable steps with working code examples to get you up and running.
Core Components You’ll Need
Your app relies on four key pieces to function:
- Audio Capture: Pull real-time input from your microphone.
- Wake Word Detection: Spot your target keyword (e.g., "Hey Python") to trigger the assistant.
- Command Recognition: Listen for and interpret the user’s request after the wake word.
- Function Execution: Run the code tied to the user’s command.
Step 1: Install Dependencies
First, install the essential libraries. Open your terminal and run these commands:
# For audio capture and basic speech recognition pip install SpeechRecognition pyaudio # For offline, low-latency wake word detection (highly recommended) pip install pvporcupine
Note: If you hit issues installing
pyaudioon Windows/macOS, you might need to install system-level audio libraries first (e.g.,portaudiovia Homebrew on macOS).
Step 2: Implement Wake Word Detection
We’ll use Porcupine (from Picovoice) for wake word detection—it’s offline, fast, and supports custom wake words. Here’s how to set it up:
- Grab a free Porcupine Access Key from Picovoice’s console (just need an email sign-up).
- Download a wake word model (use pre-built ones like "Hey Python" or create your own custom model).
Full Working Code Example
import pvporcupine import pyaudio import speech_recognition as sr # Configuration - fill in your details ACCESS_KEY = "YOUR_PORCUPINE_ACCESS_KEY" WAKE_WORD_MODEL_PATH = "path/to/your/wake-word-model.ppn" # e.g., hey-python_en_windows_v3_0_0.ppn def wake_word_detected(): """Triggered when the wake word is heard""" print("Wake word detected! Listening for your command...") recognize_user_command() def recognize_user_command(): """Listen for and process the user's request after wake word""" r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) # Cut down background noise audio = r.listen(source) try: command = r.recognize_google(audio).lower() print(f"You said: {command}") # Map commands to functions if "open calculator" in command: open_calculator() elif "tell me a joke" in command: tell_joke() elif "say hello" in command: greet_user() # Add more command-function pairs here except sr.UnknownValueError: print("Sorry, I didn't catch that. Could you repeat?") except sr.RequestError: print("Oops, I can't reach the speech recognition service right now.") def open_calculator(): import os os.system("calc" if os.name == "nt" else "open -a Calculator") print("Opening calculator for you...") def tell_joke(): print("Why don't skeletons fight each other? They don't have the guts!") def greet_user(): print("Hello there! How can I help you today?") def main(): # Initialize Porcupine wake word detector porcupine = pvporcupine.create(access_key=ACCESS_KEY, keyword_paths=[WAKE_WORD_MODEL_PATH]) # Set up audio input stream pa = pyaudio.PyAudio() audio_stream = pa.open( rate=porcupine.sample_rate, channels=1, format=pyaudio.paInt16, input=True, frames_per_buffer=porcupine.frame_length ) print(f"Listening for your wake word... (Press Ctrl+C to stop)") try: while True: pcm = audio_stream.read(porcupine.frame_length) pcm = pvporcupine.convert_pcm_to_int16(pcm) keyword_index = porcupine.process(pcm) if keyword_index >= 0: wake_word_detected() except KeyboardInterrupt: print("\nStopping the assistant...") finally: # Clean up resources porcupine.delete() audio_stream.close() pa.terminate() if __name__ == "__main__": main()
Alternative: Basic Wake Word Detection (No External Services)
If you want a simpler, no-frills solution without Porcupine, you can use SpeechRecognition in a loop to check for your wake word. Note: This is less efficient and may have more false positives.
import speech_recognition as sr WAKE_WORD = "ok python" def listen_for_wake_word(): r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) print(f"Listening for '{WAKE_WORD}'...") while True: audio = r.listen(source) try: text = r.recognize_google(audio).lower() if WAKE_WORD in text: print("Wake word detected!") your_custom_function() except sr.UnknownValueError: pass # Ignore unrecognizable audio except sr.RequestError: print("Couldn't connect to the speech service.") def your_custom_function(): print("Running my custom function!") if __name__ == "__main__": listen_for_wake_word()
Pro Tips to Level Up Your Assistant
- Reduce False Positives: Use Porcupine’s custom wake word training to create a model tailored to your voice and environment.
- Full Offline Support: Replace Google’s speech recognition with a local model like
Voskto avoid relying on internet access. - Background Listening: Wrap the listener in a thread so your app can handle other tasks while monitoring for the wake word.
- Smart Intent Recognition: For complex commands, use NLP libraries like
spaCyorRasato parse user intent instead of simple string checks. - Robust Error Handling: Add try/except blocks for microphone access issues, audio stream errors, and recognition failures.
Play around with these examples, tweak the wake word, and expand the command functions to fit your needs—you’ll have a working assistant in no time!
内容的提问来源于stack exchange,提问作者J0K3R_12QQ

