[Pythonmac-SIG] Speech Recognition example (was Re: Example of stand-alone NSRunLoop)

Joe Strout joe at strout.net
Wed Oct 15 16:27:24 CEST 2008


Thanks, Jack and Ronald.  Using currentRunLoop() or mainRunLoop()  
makes it the run loop work.

I found that I also needed to call setListensInForegroundOnly_(False),  
since a simple terminal app is never considered to be in the  
foreground, and so would not otherwise be able to listen.

With that modification, it works great!  For the archives, here's a  
complete working demo of Mac speech recognition (below).

Incidentally, it seems that SR has taken a step backwards in Cocoa.   
Carbon lets you specify a language model (i.e. grammar), which allows  
for commands with parameters for example.  The Cocoa approach is much  
more limited, only allowing you to specify a set of simple fixed  
commands.  Even the docs admit this:

> The NSSpeechSynthesizer and NSSpeechRecognizer classes provide the  
> Cocoa interface to the lower-level Carbon technologies of Speech  
> Synthesis and Speech Recognition, respectively. If you require  
> greater control of speech than permitted by the Cocoa classes, you  
> may use the underlying Carbon frameworks instead.

This is odd, since I thought Carbon was going away (not going to work  
on 64-bit machines), and Cocoa was the officially blessed API now.  
Makes me worry a bit about the whole SR functionality, which has  
always been a bit of an unwanted stepchild.  Time will tell, I guess.   
But anyway, here's the code -- thanks to all for your help.  (And if  
you spot anything in the code that doesn't follow standard Python  
idioms, please do correct me, as I'm eager to learn.)

Cheers,
- Joe

-----
#!/usr/bin/Python
#
# Stand-alone Cocoa speech recognition test.
#

from Foundation import *
import AppKit
import sys

class SRDelegate(NSObject):
	def speechRecognizer_didRecognizeCommand_(self,sender,cmd):
		print "speechRecognizer_didRecognizeCommand_", cmd
		if cmd == u"Quit the test.": sys.exit()

recog = AppKit.NSSpeechRecognizer.alloc().init()
recog.setCommands_( [
		u"Test the speech recognizer.",
		u"What is the airspeed velocity of an unladen swallow?",
		u"What is your quest?",
		u"What is the capital of Assyria?",
		u"Quit the test."])
		
recog.setListensInForegroundOnly_(False)
d = SRDelegate.alloc().init()
recog.setDelegate_(d)


print "Listening..."
recog.startListening()

# Now we need to enter the run loop...
runLoop = NSRunLoop.currentRunLoop()
runLoop.run()
-----




More information about the Pythonmac-SIG mailing list