Cameron Lane

Erstwhile educator. Python programmer.

Simple Text to Speech in Python

I wanted to make a simple counter that would speak the numbers from 1 to 100. I knew that OS X had the capability using the say command, but I wanted to use python. Thus, I came up with this little python script:

#!/usr/bin/env python
import os

for i in range(1,100):
    os.system('say %s' % i)

That's fun, but I don't really think it works as a timer or anything. This got me thinking about other interesting scripts that could make use of the say command. I can think of few things better than 'Fitter, Happier' from Radiohead's classic album, OK Computer. At any rate, here's how to do it, using a text file on my website and a python script:

#!/usr/bin/env python
import os,urllib2

URL = 'http://cameronlane.org/misc/fitter_happier.txt'
f = urllib2.urlopen(URL)
os.system('say %s' % f.read())

This works okay, but the voice is not quite right. After consulting the man pages for say on OS X, I learned that supplying the -v switch followed by a valid voice name can produce the result we want. Looking through the list in system preferences, Fred is the closest to the recording. Making the change to the relevant part of the script results in the following:

#!/usr/bin/env python
import os,urllib2

URL = 'http://cameronlane.org/misc/fitter_happier.txt'
f = urllib2.urlopen(URL)
os.system('say -v fred %s' % f.read())

foo = bar

You can download the entire script from my github gists.

comments powered by Disqus