-2

I am having some difficulty finding a solution to my problem in python. I have a function that uses text to speech, to say the given phrase. I want to be able to interrupt the function in mid process. For example, my computer is saying a very long paragraph and I want it to stop talking. How would I do this. Is it possible?

This is how I am doing the TTS:

os.system('say -v Oliver "' + text + '"')

Sincerely

4
  • Specific way to solve the problem highly depends on TTS api you are using. Commented Oct 11, 2016 at 20:12
  • Do you have an example of the code that you are trying to run? Commented Oct 11, 2016 at 20:12
  • I am using the mac TTS for example say "Hello World" @AlexeyGuseynov Commented Oct 11, 2016 at 20:13
  • So I'm guessing you want to be able to say press the 'q' key on your keyboard to exit the program? Commented Oct 11, 2016 at 20:39

1 Answer 1

2

You can use the KeyboardInterrupt exception to end the say. You need to spawn the say using Popen [function of subprocess] and attach a process ID so you can later kill it if the exception is triggered.

import signal
import subprocess

try:
    # spawn process
    proc = subprocess.Popen(["say", "-v Oliver \"{}\"".format(text)], 
            stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
    # Terminal output incase you need it
    (out, err) = proc.communicate()
except KeyboardInterrupt:
    # function to kill the subprocess
    os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
    pass

Not the answer you're looking for? Browse other questions tagged or ask your own question.