Skip to content
ImagineWorld

Voice Control AI on a Robot with Python

node_idnode-book_learn-robotics-programming_chapter-16-voice-control-ai-on-a-robot-with-python
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num16
chapter_titleVoice Control AI on a Robot with Python
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 16 — Voice Control AI on a Robot with Python

Section titled “Chapter 16 — Voice Control AI on a Robot with Python”

In previous chapters, we added behaviors and functionality to our robot. In this chapter, we’ll use voice commands to launch and control face-tracking or object-following, and have the robot report back to us in a voice of its own.

We’ll see how to install AI components to convert our speech to text and text back to speech. We’ll install a component to make use of that text with the robot’s MQTT systems and respond with useful information. This will all be running directly on the Raspberry Pi.

Voice control adds ways to control the robot without reaching for the phone, building toward robotic interfaces that are more human. This also shows more of the flexibility of using an MQTT bus to connect systems.

We will learn about components to deploy and configure, basic speech concepts like utterances, and how to build it all in Python on the Raspberry Pi.

In this chapter, you will learn about the following topics:

  • Introducing voice agents
  • Adding sound input and output to Raspberry Pi
  • Getting Python to speak
  • Speech recognition with Python
  • Connect commands to the robot

Before we get started, make sure you have the following parts:

  • The robot and its code from Chapter 15*,* Line-Following with a Camera in Python
  • A headset with a microphone and wireless USB dongle (See Appendix A*:* Shopping for R obot P arts for details)
  • A relatively quiet space for testing
  • A computer and internet access

You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book.

This chapter’s code files are included in the downloadable code bundle.

A voice agent is any program that can respond to voice requests, perform a task, and then respond with its own voice. You are likely familiar with Alexa, Siri, or Google voice agents.

When you speak to the robot, or it speaks to you, you use an utterance – a word or phrase spoken aloud. You will speak utterances to the robot, and it will speak utterances back to you.

Voice agents can be built by sending data to a larger computer on the internet, and having the system there decode speech or process the commands. However, on this robot, we will be building the voice agent locally on the robot. Why do this?

  • You can use voice commands even without an internet connection
  • It does not depend on an external service that could be unavailable

A voice agent recognizes commands and can use a number of methods to interpret your utterances:

  • Interpret exact matches
  • Have a list of synonyms to match
  • Use a small language model (AI) to match

For this chapter, we will keep things simple and use exact matches, but add in a few synonyms. Small Language Model (SLM) integration is interesting but is beyond the scope of this book.

We will integrate AI voice models to convert your utterances to text and to convert robot responses from text to voice utterances.

We have multiple options, with the voice agent running on a second Raspberry Pi, or running on the same Raspberry Pi as the robot system. At this point, we will trade off some performance to run it on the same Raspberry Pi to keep the costs low.

Another trade-off is for speech generation. This can be dynamic, generating speech from responses at the very moment it’s needed. It can also be static, with all the spoken utterances pre-generated before the program runs, so it need only play them back. The trade-off is flexibility of the dynamic systems versus the higher quality sound and less compute usage of pre-generated static systems. We will choose the flexibility of a dynamic system.

Our robot instructions are sent via MQTT, which makes interfacing relatively simple. The voice agent only needs to send one or more MQTT messages for each match. So human utterances trigger the voice agent, which publishes MQTT messages to start robot behaviors and speaks a response utterance to say it has done it.

So, the system we will build will have the following cycle:

  1. Wait for the user to speak
  2. Decode the user’s utterance into words
  3. Compare the words against a set of matches and synonyms
  4. Send MQTT commands to the robot to act on the matched words
  5. Speak an utterance confirming the action was taken

Let’s see how we will connect sound input and output to this Raspberry Pi.

Adding sound input and output to Raspberry Pi

Section titled “Adding sound input and output to Raspberry Pi”

The robot currently has no sound input or output on board. While it has connectors for headphones and the Inventor HAT Mini (the Raspberry Pi motor controller add-on board) has a speaker connection, these aren’t entirely suitable.

A microphone on the robot means you’d have to get your mouth close or shout loudly to be heard over any motor noise, and microphones respond poorly over distances of over a meter or so. The magnets in a speaker will also interfere with the IMU.

Wired headphones would mean having to stay very close to the robot and defeat the point of using Wi-Fi. We are going to need to go wireless!

Wireless USB dongle headsets come as a pair with the headset and a little box you plug in via USB. They are easy to set up and automatically recognized by the Raspberry Pi. See Appendix A*:* Shopping for Robot Parts for why this type of headset was chosen.

Let’s get this headset connected and get some audio with it!

Use these instructions to get your headset connected:

  1. Plug the Headset dongle into a blue Raspberry Pi USB port.
  2. Power on Raspberry Pi if it isn’t already.
  3. Power on the headset. After a few moments, it should let you know it is connected (use the headset manufacturer’s instructions if this doesn’t work).
  4. SSH into the Raspberry Pi
  5. We are going to test with a sound at https://github.com/pimoroni/inventorhatmini-python/blob/main/examples/audio/ahoy.wav, from Pimoroni. Download this raw to the robot with the following command:
    $ wget https://github.com/pimoroni/inventorhatmini-python/raw/refs/heads/main/examples/audio/ahoy.wav
    This will take a second or so to download.
  6. Now try playing it with the command:
    $ pw-play ahoy.wav
    You should hear audio in the headset. Note that when you first play a sound in a session, the start may be quiet as the headset powers up. Many go into a low power mode when there’s no audio being sent. If this doesn’t work, check the headset instructions to ensure you have a connection and try playing again.

We’ve been able to play audio. However, for a headset to be fully useful, we also need to record your voice from it. Let’s get that to work next:

  1. Ensure you are wearing the headset, and the mic is close to your mouth or jawbone.
  2. Type the following command in the SSH terminal:
    $ pw-record test.wav
  3. Now say something, it’s traditional to say “testing, testing, 1, 2, 3, 4” for this, but it could be anything.
  4. Press Ctrl + C when you are done.
  5. You should be able to play back your voice with the following command:
    $ pw-play test.wav

In computer audio, there’s some important terminology:

  • An audio source is an input, somewhere to get audio data. For example, a microphone or reading from an audio file.
  • An audio sink is an output, somewhere to send audio data. For example, a speaker or writing to an audio file.

If the playback is too quiet or loud, you can control this with the following command:

$ alsamixer

This shows text UI (TUI) for adjusting the volume of your output device. The up and down keys let you change the volume, and the E sc key exits this tool. You can now retry playing audio.

We’ve now managed to play audio from a file on the headset speaker, record your voice from a microphone into a file, and control the output volume of the system.

We can use this to build our robot voice agent. Let’s get our robot to talk!

We now have audio playback from the robot. We can now write some Python code that speaks utterances through our headset.

Let’s get this software running, select a voice, and create some sounds.

Speech generation is also known as speech synthesis, voice synthesizer, or text-to-speech. There’s a handy AI model-based Python voice synthesizer known as P iper TTS for this. A text-to-speech system converts input text into spoken audio.

We also need a Python library to play the audio. The Python sounddevice library works well on the Raspberry Pi for audio sinks.

We also need to choose a voice for our robot. Piper has voice samples at https://rhasspy.github.io/piper-samples/. I will use en_US‑ryan‑low for now; however, you can choose any voice you like. The names have a language, region, and then a voice name. The last part is a model quality. Low-quality models will run very quickly on the Raspberry Pi; medium- or high-quality ones might be too slow to feel responsive.

Let’s use PyInfra to install this all on our SD card. Create the file deploy/deploy_speaking.py with the following content:

from deploy import virtual_env
from pyinfra.operations import apt, pip, server
audio_packages = apt.packages(
name="Install audio hardware packages",
packages=[
"libportaudio2",
"pipewire-alsa",
],
_sudo=True
)
piper = pip.packages(
name="Install piper TTS Python packages",
packages=[
"piper-tts",
"pathvalidate",
"sounddevice",
],
virtualenv=virtual_env.robot_venv
)
if piper.changed:
server.shell("robotpython -m piper.download_voices en_US-ryan-low")

We start by installing apt packages to make the sound hardware available for Python libraries to use: libportaudio and pipewire‑alsa. We then need Python packages for text-to-speech and a Python sound device library. Piper needs pathvalidate to determine what type of hardware you have. This uses the virtual_env we created in an earlier PyInfra script, and then makes use of the pip operation to ensure Python packages are present to the robotpython command. Then the if condition checks if we installed a new package. If so, it instructs Piper to download the chosen voice using a custom shell operation.

Run pyinfra inventory.py deploy/deploy_speaking.py ‑y to deploy Piper to the robot. Add this step to deploy/deploy_all.py in case you make a robot rebuild or a second robot.

Let’s see what we have. SSH into the robot and type ls. You should see a number of files, including the following:

en_US-ryan-low.onnx.json
en_US-ryan-low.onnx
face_detection_yunet_2023mar_int8.onnx

What you might notice is that we have an onnx file for the face detection, which was downloaded in Chapter 14, Robot Vision — Using a Pi Camera and OpenCV, and we now have another onnx model for our chosen voice. Both are neural network AI models, but it is now using the network to generate audio instead of recognizing faces. There should also be an accompanying JSON file, which describes the model and provides information like sample rates.

If you do not see your chosen voice here and have previously installed Piper, you may need to (temporarily) take the if condition off of that pyinfra command to ensure it does download a model.

We can immediately use it in a command, although this will be slow, by typing the following:

$ robotpython -m piper -m en_US-ryan-low "Hello there."

It will warn about a missing GPU (expected on a Raspberry Pi), then after about 30-40 seconds say Hello there. You can change the text in the quotes.

We can build a Python library for speaking, get a faster response and have a system ready for our robot to use. The following diagram shows the data flow for this:

Figure 16.1 – Data flow for speaking

Figure 16.1 – Data flow for speaking

Figure 16.1 – Data flow for speaking

In the preceding diagram, the Voice synthesizer is initialized with a Language model, which guides its pronunciation. Then Utterances are sent to it as plain text. The Voice synthesizer will generate Audio data, which is sent to OutputStream. The OutputStream, part of the sounddevice library, sends audio through to the Speaker.

While we could let the voice model generate all the data for a sentence and send it, the system is quicker if we send voice data to the audio sink as we generate it, in chunks. This is audio streaming, and we will be using it for sources and sinks. It also has lower memory requirements, as we only need to buffer the next chunk of audio instead of a whole utterance. Let’s build our speech streaming system.

Create the new file robot/common/speaking.py with this code:

from piper import PiperVoice
import sounddevice as sd
import numpy as np
class VoiceSynthesizer:
def __init__(self):
self.voice = PiperVoice.load("en_US-ryan-low.onnx")
self.stream = sd.OutputStream(
samplerate=self.voice.config.sample_rate,
channels=1
)
self.stream.start()

This code starts by importing a PiperVoice, the sound device, and NumPy.

The VoiceSynthesizer class will hold the voice setup and output code. When the VoiceSynthesizer is created, it loads the neural network voice model into PiperVoice. Ensure this model has the same name as the one you downloaded.

We create a sound output stream (a sink), with the sample rate provided by the voice model rate and a single channel, so the voice comes out of both headphone speakers.

We start the stream, so it is ready to receive data. The stream is started, the model is ready, but it’s not saying anything yet. Let’s add a method to say things:

def speak(self, text):
for chunk in self.voice.synthesize(text):
self.stream.write(chunk.audio_float_array)
self.stream.write(
np.zeros((int(0.02 * self.stream.samplerate), 1), dtype=np.float32)
)

This VoiceSynthesizer.speak method calls voice.synthesize to generate the spoken utterance from the text. The synthesizer audio data is generated as a stream of audio chunks. We loop over the chunks until they are done.

For each chunk, we extract an audio_float_array, formatting the audio data in a way that the sounddeviceOutputStream expects. We then use stream.write to write that data over to the OutputStream. Writing it sends the audio out to our headphones.

When the loop is complete, we add a small end buffer, based on the sample rate, of zeros. Without this, sometimes the last chunk of data isn’t quite enough, so the sounddevice doesn’t play the end of the sound.

We can try this library out now. Run pyinfra inventory.py deploy/update_code.py ‑y to send it.

On your robot, via SSH, with the headphones turned on, type robotpython. You should see a Python console like the following:

Python 3.11.2 (main, Apr 28 2025, 14:11:48) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

This is ready for you to try commands. Use the following commands:

>>> from robot.common.speaking import VoiceSynthesizer
2026-04-02 20:06:31.485569247 [W:onnxruntime:Default, device_discovery.cc:325 DiscoverDevicesForPlatform] GPU device discovery failed: device_discovery.cc:92 ReadFileContents Failed to open file: "/sys/class/drm/card1/device/vendor"
>>> voice = VoiceSynthesizer()
>>> voice.speak("hello there!")
>>> voice.speak("Let's make robots.")

The first line will import and will show the GPU warning.

When you enter the line creating the voice variable, it will take a while to run; this is loading the model. After the model has loaded, typing voice.speak with a string to say makes the robot speak to you. They should run within a second or so, allowing you to try getting it to say many things. It is a small model, so it won’t pronounce everything perfectly.

Let’s ensure this works before we continue.

If you have problems running this, try the following troubleshooting methods:

  • If you hear no audio, ensure you were able to play audio back during the section Getting your headset connected.
  • I’ve found that if the robot has been quiet for a while, the first sound played is less clear as the headphones warm up. This is expected with wireless headphones.
  • If you see No such file or directory: 'en_US‑ryan‑low.onnx.json', then you either need to go back to downloading the voice model, have misspelled the model name, or need to ensure you are in the home directory for your Pi user.

You now have a speaking library ready to use for your voice agent. The next step will be teaching it to recognize utterances.

The next key component for our voice agent is recognizing things we say—our human utterances.

We will use the Vosk model-based voice recognition system, and demonstrate it recognizing words. We’ll also help our voice model along with a set of phrases we are likely to use, so our utterances are less confused with other likely-seeming versions.

Vosk is another tool that uses an AI model and can be installed for Python with pip. Vosk also has bindings for many other programming languages.

Let’s set up our PyInfra deployment to add it in deploy/deploy_speaking.py. Add the following to the end of it:

pip.packages(
name="Install vosk recognition",
packages=[
"vosk",
],
virtualenv=virtual_env.robot_venv
)

Then run pyinfra inventory.py deploy/deploy_speaking.py ‑y again to deploy this. Vosk should now be installed and ready for us to test it.

At a high level, voice recognition systems work in a symmetrical way to text-to-speech systems. See the following diagram for what we will build with it:

Figure 16.2 – Voice recognition system

Figure 16.2 – Voice recognition system

Figure 16.2 – Voice recognition system

The preceding diagram should make the symmetry clear here. The Voice recognizer is initialized with a Language model to recognize voices.

An InputStream listens for sounds from the Microphone device and sends the Audio data to the Voice recognizer. The recognizer will then generate Utterances as text from the sound frames.

Let’s build this code. Create the file robot/tests/test_vosk.py. We’ll start with a set of imports and a global sample rate:

import json
import sounddevice as sd
from vosk import Model, KaldiRecognizer
sample_rate = 44100

The KaldiRecognizer is the main recognizer component of Vosk. Vosk is built on top of the Kaldi project, simplifying its usage. We are also importing JSON, as Vosk tends to communicate with JSON.

We can then initialize the recognizer:

recognizer = KaldiRecognizer(Model(lang="en-us"), sample_rate)

This line sets up a US English language model, then uses it along with the sample rate to initialize the recognizer. We then set up the input stream, listening on the mic:

with sd.InputStream(samplerate=sample_rate, channels=1, dtype="int16") as stream:

This has the same sample rate as the model, a single channel, so it’s monophonic, and dtype specifies an int16 datatype, suitable for the recognizer.

We can now start a loop, passing data to the recognizer and checking if we have got something:

while True:
audio_data = stream.read(int(0.2 * sample_rate))
if recognizer.AcceptWaveform(audio_data[0].tobytes()):
result = json.loads(recognizer.Result())
if result.get("text"):
print("Recognized:", result['text'])
else:
result = json.loads(recognizer.PartialResult())
if result.get('partial', ''):
print("Partial:", result['partial'])

This while loop is indented to be within the with sd.InputStream statement. This loop starts by reading in 0.2 seconds of audio, which it then passes to the voice recognizer.

The loop checks if the recognizer has a result, which it will if the user has been talking and has finished. Otherwise, if the user is still talking, there is only a PartialResult. The PartialResult has the words spoken so far, which is useful for debugging purposes.

For either the Result or PartialResult, Vosk returns these as JSON, which we must load. We check if the result is not empty (when the user says nothing) and print anything we get.

Run pyinfra inventory.py deploy/update_code.py ‑y to deploy the new code. Ensure your headphones are connected and on, then run it with SSH to see results:

$ robotpython robot/tests/test_vosk.py

You can now start talking to the robot, and you will see it recognizing:

Partial: robot
Partial: robot follow
Partial: robot follow
Partial: robot follow lines
Recognized: {'text': 'robot follow lines'}
Partial: robot
Partial: robot stop
Partial: robot stop following
Partial: robot stop following lines
Recognized: {'text': 'robot stop following lines'}

You will see more repetition than this, but you can see it getting partial results, then finding sentences. However, it might get things wrong:

Partial: robot
Partial: robot track
Partial: robot track faces
Recognized: {'text': 'robot track faces'}
Partial: rebels
Partial: rebels stop
Partial: rebels stop tracking
Partial: rebels stop tracking faces
Recognized: {'text': 'rebels stop tracking faces'}

I was saying robot, but it’s matching a broad vocabulary, including the word rebels. I could slow down and talk more clearly, but we can also make the model better. I don’t think we are looking for rebel robots here.

Let’s make sure this is working for you.

Try these troubleshooting steps:

  • If you have audio problems, please ensure you were able to record your voice in the Getting your headset connected section.
  • If you see errors, please double-check your code.
  • If it is not picking up much voice, please try to get the mic closer to your mouth.
  • If it is getting the words wrong, i.e., things that sound close but are not what you meant, that is expected at this stage and will be resolved in the next step.

We are now ready to tune this voice recognizer. Press Ctrl + C when you are done. Let’s tune it to recognize words relating to our robot.

The recognizer lets us specify a vocabulary of utterances to recognize, including single words or whole phrases. Since we are going to use matching and synonyms, we can pass whole phrases and have this work correctly.

Open robot/tests/test_vosk.py, and after the sample rate, add the highlighted vocabulary:

sample_rate = 44100
utterances = [
"robot",
"start tracking faces",
"track faces",
"start following lines",
"follow lines",
"start tracking objects",
"track objects",
"start object tracking",
"start face tracking",
"stop",
]

This is not exhaustive, but certainly approaching a list of things we might say to this robot. We can pass this into the recognizer by making the highlighted change:

recognizer = KaldiRecognizer(Model(lang="en-us"), sample_rate, json.dumps(utterances))

This has to be converted into JSON for Vosk to work with it.

Redeploy with pyinfra inventory.py deploy/update_code.py ‑y and try speaking to it again. It will now be constrained to recognizing items in the vocabulary only. It won’t be mismatching robot as rebel.

This still has a problem though. If I start saying nonsense like banana teapot to it, it should print nothing; however, I got the following for that:

Partial: lines
Partial: lines
Partial: lines
Partial: lines track objects
Partial: lines track objects
Partial: lines robot
Partial: lines robot
Recognized: lines robot

As you can see, it’s trying hard to fit what we say to one of its commands. This is called overfitting, and it can be a problem: any casual word is being forced into a command.

Vosk has a special vocabulary item we can add:

utterances = [
"robot",
"start tracking faces",
"track faces",
"start following lines",
"follow lines",
"start tracking objects",
"track objects",
"start object tracking",
"start face tracking",
"stop",
"[unk]"
]

This [unk] is short for unknown. It stands for anything else in the larger model vocabulary and will result in the recognizer showing the [unk] placeholder, too:

Partial: [unk]
Recognized: [unk]

This is good enough to start building our voice agent.

When a voice agent is listening, it may partially match anything you say. We would like this robot to only respond to phrases that start with its name, in our case robot. The voice agent system is always listening when it’s running, but will only try to match instructions after a special phrase known as a wake word. That makes it a special part of the utterances list. We can check our recognized items to ensure they start with this word and only print those that do.

Technically, wake words can be used to start a listener with a larger model, but we are going to keep it simple and just match the start of our recognized text.

We can also use the same moment to filter out any matches with [unk] in them as invalid.

First, we declare the wake word and unknown as variables, pulling them out of the utterances list:

wake_word = "robot"
unknown = "[unk]"
utterances = [
"start tracking faces",
"track faces",
"start following lines",
"follow lines",
"start tracking objects",
"track objects",
"start object tracking",
"start face tracking",
"stop",
]
full_vocabulary = utterances + [wake_word, unknown]
recognizer = KaldiRecognizer(Model(lang="en-us"), sample_rate, json.dumps(full_vocabulary))

The list for the recognizer is still the same, but these two variables can be used differently. Find the section starting with if recognizer and make the highlighted changes:

if recognizer.AcceptWaveform(audio_data[0].tobytes()):
result = json.loads(recognizer.Result())
text = result.get('text', '')
if text.startswith(wake_word) and unknown not in text:
print("Recognized:", text)
else:
result = json.loads(recognizer.PartialResult())
partial = result.get('partial', '')
if partial.startswith(wake_word):
print("Partial:", partial)

Here we’ve extracted the text or partial match. For the text, instead of checking that it’s not empty, we now check if it starts with our wake word and doesn’t have unknowns in it.

For the partial match, we are being a bit less strict and only check that it starts with the wake word. That means that if you speak sentences that don’t start with the word ” robot,” it will ignore that line.

Let’s redeploy and rerun this. You can now try phrases it expects, and phrases like “robot teapot banana,” and see it ignore the nonsense phrase:

Partial: robot
Partial: robot
Partial: robot follow lines
Recognized: robot follow lines
Partial: robot
Partial: robot [unk]

This output shows it recognizing a phrase I spoke; however, the second included the nonsense phrase, so it only ever makes a partial match and discards it. Any phrase not starting with robot is ignored.

We have now tested the voice recognizer enough to start building an agent with it.

We are going to combine our speech, our voice recognition, and an MQTT behavior to make a voice agent on the robot. When this is running, it will be able to launch or stop behaviors based on our voice input.

Do not rely on voice commands to stop a robot’s behavior! It will never be as quick as a S top button.

Let’s design this app.

The following diagram shows a rough outline of our app:

Figure 16.3 – Voice agent app outline

Figure 16.3 – Voice agent app outline

Figure 16.3 – Voice agent app outline

The preceding diagram shows the app we will build for a voice agent. The app starts with some Setup, preparing voice models and MQTT.

When the app has been set up, it will then Wait for a voice command using the recognizer techniques we learned earlier in this chapter.

Based on the voice commands, it will have matched an utterance to some kind of task. The tasks in our system are all on the robot and will result in it sending one or more MQTT messages. When the robot has sent the messages, it will Speak to the user to inform the user it has carried out the task.

We will build this as a class-based behavior, and we will need to use a Queue so the device input doesn’t get stuck. We last used these in Chapter 14, Robot Vision — Using a Pi Camera and OpenCV for the camera frame buffer.

Create the file robot/voice_agent.py, and we’ll start by adding in the imports:

import json
import sounddevice as sd
from vosk import Model, KaldiRecognizer
from common.speaking import VoiceSynthesizer
from common.mqtt_behavior import connect

We will also define a few constants:

sample_rate = 44100
unknown = "[unk]"
wake_word = "robot"

With those ready, we’ll build our voice agent. We’ll start with two commands initially, then expand it:

class VoiceAgent:
def __init__(self):
self.synthesizer = VoiceSynthesizer()
self.client = connect()
self.utterances = {
"start tracking faces": self.start_tracking_faces,
"stop tracking faces": self.stop_tracking_faces,
}
full_vocabulary = list(self.utterances.keys()) + [wake_word, unknown]
self.recognizer = KaldiRecognizer(
Model(lang="en-us"),
sample_rate,
json.dumps(full_vocabulary)
)

This code connects first to MQTT. Then we create a dictionary of utterances, with the right-hand side naming a function we’ll create for each. We can link any number of utterances this way.

As we did in the test code, we append the wake word and unknown word holder to this list. This is much of the setup prepared.

Let’s add a main loop, representing the loop shown in the design:

def start(self):
self.synthesizer.speak("Robot ready for commands.")
with sd.InputStream(samplerate=sample_rate, channels=1, dtype='int16') as stream:
while True:
audio_data = stream.read(int(0.2 * sample_rate))
command = self.recognize_audio(audio_data)
if command:
self.handle_command(command)

The start method first tells the user it’s ready for commands, with a call to self.synthesizer.speak. It then initializes the InputStream.

This loop will then check for audio data, recognize this data, and handle a command (if there was one). We’ll need to fill out these methods:

We’ll start with recognize_audio:

def recognize_audio(self, audio_data):
if self.recognizer.AcceptWaveform(audio_data[0].tobytes()):
result = json.loads(self.recognizer.Result())
text = result.get('text', '')
if text.startswith(wake_word) and unknown not in text:
return text
else:
result = json.loads(self.recognizer.PartialResult())
if result.get('partial', ''):
print("Partial:", result['partial'])
return None

This is similar to the code we used when testing, but now it returns text when we find a match; otherwise, it returns None. That way, if the user says nothing, or something that doesn’t match conditions, no command will be launched.

The next method we need is one to handle a command:

def handle_command(self, command):
print("Handling command:", command)
command = command.replace(f"{wake_word} ", "")
task = self.utterances.get(command)
if task:
print("Running command:", command)
task()
else:
self.synthesizer.speak("I didn't understand that task.")

The handle_command method first takes the wake word out of the command, since that has already been matched. We then fetch a task (or a method to call) from the table of utterances by the command we received.

We check that we were able to find something in the table, and if we do, we run that task. If there’s no match, the voice agent will speak to inform the user.

We are almost there. We now need to add the task methods for tracking faces:

def start_tracking_faces(self):
self.client.publish("launcher/start", "face_detector")
self.client.publish("launcher/start", "look_at_face")
self.synthesizer.speak("I'm now looking at faces!")
def stop_tracking_faces(self):
self.client.publish("launcher/stop", "face_detector")
self.client.publish("launcher/stop", "look_at_face")
self.synthesizer.speak("I'm no longer looking at faces.")

The task methods are simple; they publish some MQTT messages, then speak to the user.

We can now finish this file:

behavior = VoiceAgent()
behavior.start()

Let’s upload this initially with pyinfra inventory.py deploy/update_code.py ‑y.

We can manually run it and hear it working. Wear your headset so you are ready when it starts. Then SSH into the robot and type:

$ robotpython robot/voice_agent.py

After a minute or so, you will hear the disembodied “Robot ready for commands” voice in your headphones.

You can say “robot start tracking faces”, and you should see the servo motors move along with a voice response. You now have three neural network AI models running together on your Raspberry Pi! One is recognizing faces, another is recognizing voices, and the third is synthesizing a voice to respond. When you are done, say “robot stop tracking faces” and it should stop the motors from moving and speak to you to tell you it’s done.

If this doesn’t appear to be working, try the following:

  • Ensure that you have all previous examples working.
  • You will need to speak clearly, and you must use the exact phrase in the utterances list. Synonyms will not work yet.
  • Check for errors in the journalctl log.
  • Check for typos in the code.

Press C trl + C when you are done testing this. We have a simple voice agent, but it could do with expanding. It also will not start when the robot starts.

Starting the voice agent when the robot starts

Section titled “Starting the voice agent when the robot starts”

The voice agent is a little different from our other robot services. Access to the headset and microphone requires that it behave like a logged-in user, not as a root service.

We’re going to need to make some modifications to our deploy/service_template.j2 for this to work.

Add the highlighted lines to the Service section:

[Service]
Type=simple
Restart={{ restart }}
WorkingDirectory=/home/{{ pi_user }}/
ExecStart=/usr/local/bin/robotpython -u {{ command }}
KillSignal=SIGINT
TimeoutStopSec=2
User={{ service_user }}
Environment="XDG_RUNTIME_DIR=/run/user/{{ service_uid }}"

We are modifying this service to run as a provided service_user, which we can pass in. We are also setting an environment variable XDG_RUNTIME_DIR to a folder containing that user’s ID.

We’ll need to provide these new variables. Open deploy/deploy_services.py and add the following import:

from pyinfra.operations import files, systemd
from pyinfra import host
from pyinfra.facts import server

Next, find the function def deploy_service. We’re going to add a new optional user parameter:

def deploy_service(service_name, command, auto_start, changed, user="root"):

This user parameter will default to root if we don’t specify it, which means other services will continue working.

Now, find the unit_file section in that function. Make the highlighted changes:

unit_file = files.template(
name=f"Create {service_name} service",
src="deploy/service_template.j2",
dest=f"/etc/systemd/system/{service_name}.service",
pi_user=host.data.get('ssh_user'),
service_name=service_name,
command=command,
restart=restart,
service_user=user,
service_uid=host.get_fact(server.Users).get(user).get('uid'),
_sudo=True
)

We’ve added a service_user parameter for the template here. It has to be called service_user since there’s another user parameter for this template function that we don’t intend to use.

We’ve also specified a service_uid. A uid, or user ID, is an identity number for each user on a Linux system like Raspberry Pi OS. We use our host facts to get the user ID corresponding to the named user.

We can now add the voice agent as a service in deploy/deploy_services.py:

code = files.put(
name="Update the voice agent code",
src="robot/voice_agent.py",
dest="robot/voice_agent.py"
)
deploy_service("voice_agent", "robot/voice_agent.py",
True, common.changed or code.changed,
user=host.data.get('ssh_user'))

This will now start when the robot starts. Let’s get it deployed with pyinfra:

$ pyinfra inventory.py deploy/deploy_services.py -y

With the voice agent running when the Raspberry Pi starts, it will now start when the robot is powered on, assuming the headphones can connect to it. Put the headset on and try (via SSH) the command:

$ sudo reboot

Warning: This will take a minute or so, and the robot may startle you when it says ready for commands!

However, you still might have found yourself testing with phrases that didn’t quite match the expected ones, and the robot saying it didn’t understand. Let’s fix that.

As mentioned in troubleshooting, this currently only accepts an exact word-for-word match. However, we can extend our utterances dictionary with synonyms for a task in a fairly simple way. Open robot/voice_agent.py and find the utterances dictionary, then insert these further synonyms (highlighted):

"start tracking faces": self.start_tracking_faces,
"start face tracking": self.start_tracking_faces,
"track faces": self.start_tracking_faces,
"stop tracking faces": self.stop_tracking_faces,
"stop face tracking": self.stop_tracking_faces,

By adding utterances that have the same tasks linked to them, we create synonyms. You can add any you can think of for this.

What about adding more commands?

Adding more commands needs two parts: extending the utterances dictionary, then providing the task functions. We can follow the pattern we’ve laid down already.

Let’s extend the utterances dictionary first:

"start following lines": self.start_following_lines,
"follow lines": self.start_following_lines,
"stop following lines": self.stop_following_lines,

This example adds line following, including a synonym to the utterances list.

At the bottom of the class, before we start the behavior, we can add the matching task methods for these:

def start_following_lines(self):
self.client.publish("launcher/start", "line_detector")
self.client.publish("launcher/start", "line_follower")
self.synthesizer.speak("I'm now following lines!")
def stop_following_lines(self):
self.client.publish("launcher/stop", "line_follower")
self.client.publish("launcher/stop", "line_detector")
self.synthesizer.speak("I'm no longer following lines.")

This pattern is quite repetitive, but simple to extend. You now have a robot you can command with your voice.

In this chapter, we learned about voice agents, voice recognition, and synthesis. We connected a headset to our Raspberry Pi and figured out how to record and play back audio with it.

We then used the Piper TTS library to synthesize a voice using a neural network model. Our robot was able to speak to us!

We learned how to install and use the Vosk library to recognize voice phrases, tuning recognition to match a known set of commands while avoiding overfitting.

Finally, we brought synthesis, recognition, and MQTT messaging together to create a robot.

In the next chapter, we are going to revisit localization and sensor fusion, where we will bring more of the robot’s sensors into play with Monte Carlo localization, improving the robot’s ability to locate itself in a space.

The following challenges will let you build a better robot and learn more from the techniques in this chapter:

  • Try adding other menu items, for example, the face direction behavior.
  • Add command synonyms to them to make them easier to use, for example, “look at my face” for face tracking.
  • Change the wake word to something more fun or personalized instead of “robot”.
  • Try other voices, Alan (English UK) and Amy (English US) are good. Explore voices with https://rhasspy.github.io/piper-samples/.
  • As an advanced challenge, when it starts tracking faces, get it to listen for the face detections and speak “hello there!” when the robot first spots your face. You’ll need to add MQTT handlers and an on connect call for this to work.

Please refer to the following for more information: