Hardware Reference
In-Depth Information
import subprocess
def say(words):
#Speaks words via espeak text to speech engine
devnull = open(“/dev/null”, “w”)
subprocess.call([
“espeak”,
“-v”, “en-rp”, # english received pronunciation
↵
words],
stderr=devnull)
Let's take a brief tour of the code. The first line imports the subprocess module that allows
other programs to be called. Put simply, a program running on a computer is called a
process,
so if it wants to run another program, then (similar to calling a function) it creates another
subprocess with a call.
def
defines the
say
function that is passed a string of words to say. Next, the file
/dev/
null
is opened for writing. On Linux,
/dev/null
is a special file that throws away anything
written to it. It's a really good way of ignoring any output produced. In this case, it's used to
hide any error messages produced by espeak. If you replaced
/dev/null
with a real file-
name, then any error message would be saved there instead.
Finally, the
subprocess.call
function calls the program
“espeak”
with an array of argu-
ments to pass to it. In this case, if the
words
argument contained
hello
, it would be the
same as typing the following:
espeak -v en-rp hello
This shows that multiple arguments can be passed to a command. The
-v en-rp
is used to
specify how espeak sounds. It can be fun to play around with different pronunciations, or
even languages.
Testing the Espeak module
Now is a good time to check the Python module you've just created. Enter the following into
the file
try_espeak.py
:
#!/usr/bin/env python
# try_espeak.py
# Show use of espeak.py
import espeak as talker
def main():
talker.say(“Hello World”)