Sure! Here's a simple working Python script that does the following:
- Converts text to speech (TTS) using
gTTS or pyttsx3.
- Simultaneously listens to the microphone input.
- Detects if the user starts speaking.
- Stops TTS as soon as voice is detected.
We'll use:
pyttsx3 for Text-to-Speech (offline and easy to interrupt).
speech_recognition and pyaudio for listening to audio input.
threading to run both TTS and voice detection in parallel.
✅ Requirements
Install dependencies first:
pip install pyttsx3 SpeechRecognition pyaudio
🧠 Code: Text-to-Speech with Voice Interruption
import pyttsx3
import speech_recognition as sr
import threading
import time
# Global flag to control TTS playback
tts_active = True
def speak(text):
global tts_active
engine = pyttsx3.init()
tts_active = True
engine.say(text)
engine.runAndWait()
tts_active = False
def listen_for_speech():
global tts_active
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Listening for speech...")
while True:
try:
# Listen for a short duration to detect voice
audio = recognizer.listen(source, timeout=0.5, phrase_time_limit=1)
# If audio is captured, assume user is speaking
if tts_active:
print("User started speaking. Stopping TTS...")
tts_active = False
except:
# No speech detected
pass
# Start the listener thread
listener_thread = threading.Thread(target=listen_for_speech, daemon=True)
listener_thread.start()
# The text you want to speak
text_to_speak = "Hello, I am your assistant. I will stop talking when you start speaking."
# Run TTS in the main thread
speak(text_to_speak)
print("Program ended.")
🔍 How it Works:
- The
speak() function uses pyttsx3 to read out loud.
- In parallel,
listen_for_speech() listens for any audio input.
- As soon as voice is detected (i.e., the user starts speaking), it sets
tts_active = False.
- This causes
pyttsx3 to stop by calling engine.stop() internally via runAndWait().
⚠️ Notes:
- You can't reliably interrupt
gTTS since it plays pre-generated audio files. That’s why we're using pyttsx3 here.
- Make sure your microphone is working and not muted.
- You might need to adjust thresholds or timeouts depending on your environment.
Would you like a version using gTTS and pygame for playing audio with more control?