My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
Examples  

Featured
Updated Feb 4, 2010 by gundl...@gmail.com

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 reference

speech module functions:

  • speech.say(phrase): speak out loud.
  • speech.input(prompt=None, phraselist=None): print the prompt, then return the phrase heard from the phraselist. Blocks the thread.
  • speech.listenforanything(callback) -> Listener: when any dictation is heard, run the callback on a separate thread (see below for details). Doesn't block the thread.
  • speech.listenfor(phraselist, callback) -> Listener: when any string in the given list of phrases is heard, run the callback on a separate thread (see below for details.) Doesn't block the thread.
  • speech.islistening(): True if any Listeners are listening.
  • speech.stoplistening(): stops all Listeners.

Format of the callback function passed to listenfor() and listenforanything():

  • callback(heard_phrase, Listener): First arg is a string containing the text of the phrase that was heard. Second arg is the Listener that heard the phrase -- the same Listener that was returned by listenfor() in the first place.

Listener instance methods (call these on the object returned by listenfor() or passed to the callback):

  • islistening(): True if the Listener hasn't been stopped yet.
  • stoplistening(): stops the Listener. You can't start it again after that.

Simplest example

Whenever 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":
        break

Note 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-blocking

speech.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 functionality

See 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()
Comment by irz...@gmail.com, Sep 19, 2008

i got error after complete all the recognition: it seems this error is produced by speech.stoplistening()

Traceback (most recent call last):

File "C:\Python24\example2.py", line 47, in -toplevel-
speech.stoplistening() # stop all remaining listeners
File "C:\Python24\lib\speech.py", line 179, in stoplistening
return any(returns) # was at least one listening?
NameError?: global name 'any' is not defined

any ideas?

Comment by project member gundl...@gmail.com, Sep 22, 2008

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:

if x:
return True
else:
return False

and you should be good to go.

Comment by igw...@gmail.com, Feb 18, 2009

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

Comment by project member gundl...@gmail.com, Feb 18, 2009

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!

Comment by project member gundl...@gmail.com, Feb 18, 2009

(And of course, you'll need to sleep after this, or loop until "exit" is spoken, or something -- otherwise the program will immediately terminate.)

Comment by igw...@gmail.com, Feb 19, 2009

Alright, seems to work swell. Thanks!

Comment by lionelst...@gmail.com, Mar 29, 2009

Hi Michael, just a simple question, is it possible to use pyspeech in french? if yes how to parametrize? thanks Lionel

Comment by project member gundl...@gmail.com, Mar 30, 2009

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

Comment by lionelst...@gmail.com, Mar 30, 2009

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

Comment by project member gundl...@gmail.com, Apr 2, 2009

Hi Lionel,

I did not understand you. Are you able to make pyspeech understand French?

Michael

Comment by BoJaN4...@gmail.com, May 2, 2010

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?

Comment by BoJaN4...@gmail.com, May 2, 2010

after much trial, error and searching, I finally found the solution on google! you can use "somephrase +"

Comment by project member gundl...@gmail.com, May 3, 2010

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.

speech.listenfor(["I like * *"], callback)

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.

speech.listenfor(["I like *+"], callback)

will retrieve phrases like "I like the big while elephant because it is cute".

Comment by animatio...@gmail.com, Jun 15, 2010

speech.input("fdgfdgfg") fdgfdgfg

Traceback (most recent call last):

File "<pyshell#1>", line 1, in <module>
speech.input("fdgfdgfg")
File "C:\Python25\lib\speech.py", line 162, in input
listener = listenforanything(response)
File "C:\Python25\lib\speech.py", line 193, in listenforanything
return startlistening(None, callback)
File "C:\Python25\lib\speech.py", line 222, in startlistening
context = recognizer.CreateRecoContext?()
File "C:\Python25\lib\site-packages\win32com\gen_py\C866CA3A-32F7-11D2-9602-00C04F8EE628x0x5x0.py", line 2468, in CreateRecoContext?
ret = self.oleobj.InvokeTypes?(10, LCID, 1, (9, 0), (),)
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

Comment by project member gundl...@gmail.com, Jun 15, 2010

This means that Windows does not support your language. Sorry! Try the dragonfly Python module and see if you have better luck.

Comment by enzo.one...@gmail.com, Apr 4, 2011

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

Comment by eng.ali....@gmail.com, Mar 4, 2012

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):

File "H:/G_Project/New folder/speech", line 1, in <module>
import speech
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 >

Comment by BrianSch...@gmail.com, Apr 12, 2012

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.


Sign in to add a comment
Powered by Google Project Hosting