Pergunta

Hi I am experimenting with Speech Synthesis on mac, and I always put while loops in my programs so that I can use them until I decide to stop, and with this code, it repeats "What would you like me to say?" At the same time it says whatever I tell it to say.

from Cocoa import NSSpeechSynthesizer
while 1==1
    sp = NSSpeechSynthesizer.alloc().initWithVoice_(None)
    sp.startSpeakingString_("What would you like me to say?")    
    say_1 = raw_input("What would you like me to say?")
    sp.startSpeakingString_(say_1)

Can someone tell me how to tell python to wait until it is done saying what I tell it to?

Foi útil?

Solução

It seems you are looking for NSSpeechSynthesizer instance method: isSpeaking. You can write a polling loop to test if it is speaking and continue to work once it is not anymore. Something like this:

import time
from Cocoa import NSSpeechSynthesizer
while 1:
    sp = NSSpeechSynthesizer.alloc().initWithVoice_(None)
    sp.startSpeakingString_("What would you like me to say?")    
    say_1 = raw_input("What would you like me to say?")
    sp.startSpeakingString_(say_1)
    
    while sp.isSpeaking():    # loop until it finish to speak
        time.sleep(0.9)       # be nice with the CPU
    
    print 'done speaking'

UPDATE: Is better time.sleep than continue inside the loop. The latter will waste a lot of CPU and battery (as pointed out by @kindall).

Hope this helps!

Outras dicas

The problem is that the speech API does the speaking asynchronously. I don't know anything about this particular API, but to get this code working you'd have to poll in a loop or find an argument that specifies that your call should block. This issue is specifically connected to way this API works.

For this task, assuming you're using a Mac, you could use the command line instead. This will wait for the speech to finish before continuing.

import subprocess

def say(text):
    subprocess.call(["say", text])

print("Before")
say("Wait for me!")
print("After")
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top