How can I interrupt or stop pyttsx3 while it is speaking something?

81 Views Asked by At

I am using pyttsx3 for a voice assistant. I want to stop while it is speaking. I tried many solutions given in Stack Overflow. I even asked this query to ChatGPT, Bing AI, Bard. But it did not work.

1

There are 1 best solutions below

2
mepro On

There is no way to stop pyttsx3 from playing your sound; instead, you should consider using gTTS and pygame mixer. You can modify the following code to your liking.

from gtts import gTTS
from pygame import mixer
import time
mixer.init()

audio = gTTS("this is a test text, and will be interrupted.", lang="en")
audio.save("temp.mp3")
mixer.music.load("temp.mp3")
mixer.music.play()
time.sleep(0.5)
mixer.music.stop()

What this code will do is fetch the sound file for your text and then play it. After 0.5 seconds, it will stop playing the audio.

You need to install gtts and pygame for this to work:

pip install gtts
pip install pygame