|
Examples
If you have any trouble with the examples below, please leave a comment about it, and I or another user will be glad to help you out. Quick referencespeech module functions:
Format of the callback function passed to listenfor() and listenforanything():
Listener instance methods (call these on the object returned by listenfor() or passed to the callback):
Simplest exampleWhenever you say the name of a dwarf, it says it back, until you say "turn off". Your program can't do anything else while it's waiting for speech. import speech
while True:
phrase = speech.input("Say the name of a dwarf.",
['Sleepy', 'Happy', 'Dopey', 'Killer', 'Sneezy', 'Bashful', 'Doc', 'turn off'] )
speech.say("You said %s" % phrase)
if phrase == "turn off":
breakNote that speech.input() will only return when you say something in the given phraselist. If you don't pass in a phraselist, speech.input() will accept anything at all. Simple example, non-blockingspeech.input() in the above example blocks the program until it hears you. Below is the same example using non-blocking listeners, so that your program can do other things while waiting for speech input. import speech
def response(phrase, listener):
speech.say("You said %s" % phrase)
if phrase == "turn off":
listener.stoplistening()
listener = speech.listenfor(
['Sleepy', 'Happy', 'Dopey', 'Killer', 'Sneezy', 'Bashful', 'Doc', 'turn off'],
response)
# Your program can do whatever it wants now, and when a dwarf's name is heard,
# response() will be called on a separate thread. This can happen over and over --
# as long as the listener hasn't been stopped.
import time
while listener.islistening():
time.sleep(1)
print "Still waiting..."The example above uses 8 phrases, but you can use as many phrases as you wish; I've successfully used 12,000 sentences! Using listenforanything()Just as speech.input() can leave out the phraselist to accept general dictation, if you replace the listenfor call above with listener = speech.listenforanything(response) then speech will call the response callback as soon as any recognizable speech is heard. Using all functionalitySee the inline comments and assertions. import speech
response = ''
while response.lower() != 'uncle':
speech.say("Say uncle!")
response = speech.input()
# Handle a specific set of heard phrases with a callback.
def L1callback(phrase, listener):
print "Heard the phrase: %s" % phrase
L1 = speech.listenfor(["any of", "these will", "match"], L1callback)
# You can listen for multiple things at once, doing different
# things for each.
def L2callback(phrase, listener):
print "Another phrase: %s" % phrase
L2 = speech.listenfor(["good morning Michael"], L2callback)
# You can listen for general dictation as well. You can
# stop listening using the callback's second argument.
def L3callback(phrase, listener):
speech.say(phrase) # repeat it back
if phrase == "stop now please":
listener.stoplistening()
L3 = speech.listenforanything(L3callback)
# All callbacks get automatically executed on a single separate thread.
# Meanwhile, you can just do whatever with your program, or sleep.
# As long as your main program is running code, speech will keep
# listening.
import time
while L3.islistening(): # till "stop now please" is heard
time.sleep(1)
assert not L3.islistening()
assert speech.islistening() # to anything
print "Dictation is now stopped, L1 and L2 are still going."
L1.stoplistening()
print "Now only L2 is going"
# Listen for L2 for a while more, then turn it off.
time.sleep(30)
speech.stoplistening() # stop all remaining listeners
assert not speech.islistening()
|
i got error after complete all the recognition: it seems this error is produced by speech.stoplistening()
Traceback (most recent call last):
NameError?: global name 'any' is not definedany ideas?
Yes! any() is a Python2.5-only construct, I believe, and you're using Python2.4. Silly me. Replace speech.py line 179 with
for x in returns:
else:and you should be good to go.
Hey, I've spent the last couple days trying to get some on/off by voice command functionality into the program - and have pretty much failed. Is this something you have already figured out? Just to be clear, basically I want to say "Stand by" and have the only command recognized after that be "Computer," and if that is said, have full recognition return. I've also been trying with Inigo Surguy's code as well, still no success. Thanks fun code though, works great until I start scripting. :) Ian
That should work fine. If I understand you, you are writing a program that has several speech commands, and you wish to disable speech recognition via "stand by", at which point none of your speech commands have an effect; then later say "computer", at which point all speech commands work again. Right?
I'd suggest a decorator on your callbacks, which makes them do nothing if the system is in standby mode. Something like this (untested code):
Something like the following may work for you (untested code):
import speech speech.standing_by = False def pausable(f): "Decorator that causes callbacks to pause when Standing By." def newf(phrase, listener): if speech.standing_by: return # Pretend we heard nothing else: return f(phrase, listener) return newf @pausable def some_callback(phrase, listener): pass # do some stuff @pausable def some_other_callback(phrase, listener): pass # do some stuff @pausable def stand_by(phrase, listener): speech.standing_by = True # Note that this callback is *not* pausable, because we want it to run # when someone says "computer" even when we are standing_by def wake_up(phrase, listener): speech.standing_by = False L1 = speech.listenfor(["explode"], some_callback) L2 = speech.listenfor(["fly to the moon"], some_other_callback) L3 = speech.listenfor(["stand by"], stand_by) L4 = speech.listenfor(["computer"], wake_up)Let us know how this works for you!
(And of course, you'll need to sleep after this, or loop until "exit" is spoken, or something -- otherwise the program will immediately terminate.)
Alright, seems to work swell. Thanks!
Hi Michael, just a simple question, is it possible to use pyspeech in french? if yes how to parametrize? thanks Lionel
Hi Lionel,
pyspeech will work without change in any language that Microsoft Windows Speech Recognition can understand. If you are able to get your computer to, for instance, accept French dictation into Windows Notepad, then you should be able to use pyspeech without a problem. Please let us know how it goes!
Michael
Hi Michael,
I confirm, it works perfectly in french without the need to parametrize more!just that I tested on one word that should have been badly recognized and thougth it wasn't possible to mix french and english. cheers
Lionel
Hi Lionel,
I did not understand you. Are you able to make pyspeech understand French?
Michael
works as a wildcard but will only acts as a placeholder eg("volume one hundred" is heard as "volume one" if the phrase is "volume "
Is there a way to have it "hear" everything after a certain phrase?
after much trial, error and searching, I finally found the solution on google! you can use "somephrase +"
I reread your comment a bit and understood it more. Here's what I think you were saying:
To match a single word, you can use *, e.g.
will retrieve phrases like "I like the big" and "I like a good" and "I like it when". To match any number of words, you can use *+, e.g.
will retrieve phrases like "I like the big while elephant because it is cute".
speech.input("fdgfdgfg") fdgfdgfg
Traceback (most recent call last):
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147221164), None)i got the error like that can some one please help me out of this. thanks in advanced
This means that Windows does not support your language. Sorry! Try the dragonfly Python module and see if you have better luck.
how to prevent Windows from automatically convert my speech into commands. eg. i say 'end', then Windows recognize as 'press down end key'. these stuff bother me a lot
fist, thank you very much for your great effort . iam anew to python i have aproplem i using this code when i run it i get " Traceback (most recent call last):
ImportError?: No module named speech" although i have downloades speech-0.5.2-py2.5.egg and speech-0.5.2-py2.4.egg and put two of them with the source code please help >
I figured out how to disable windows system commands. In speech.py you need to change line 66 to:
recognizer = win32com.client.Dispatch("SAPI.SpInProcRecognizer?") recognizer.AudioInputStream? = win32com.client.Dispatch("SAPI.SpMMAudioIn")
and you also need to change line 112 to: ListenerBase? = win32com.client.getevents("SAPI.SpInprocRecoContext?")
This also disables the widget that pops up.