Creating a text to speech server w/ Python

A short little article on using Python and MQTT server to send messages to a text to speech server on my MacBook Air.

I was looking for a nice sounding text to speech agent one day and started to do a little research. I tried Amazon Polly and Google Text to Speech. They were ok to use but they require me to connect to their services. Then I realized that the voices that Apple includes in all copies of MacOS X. The command on MacOS was super simple – “say -v {voice} {string to say}”. After playing with the say command I found the right voice – A nice aussie voice named Karen.

A sample of Karen’s voice

Now it was time to put together some Python code to read from the MQTT server on my local linux server and play the message on my MacBook Air.

my TTS Server version 1.5
Description: A Text to Speech server for Mac
Revision notes: 1.5 is implementing mqtt client for text to speak
import paho.mqtt.client as mqtt
import os
import sys
import signal
def signal_handler(signal, frame):
global interrupted
interrupted = True
signal.signal(signal.SIGINT, signal_handler)
def on_connect(client,userdata,flags,rc):
print "We connected - " + str(rc)
def on_message(client,userdata,msg):
print msg.topic+" "+str(msg.payload)
os.system('say -v Karen "'+str(msg.payload)+'"')
def say_message(themsg):
print themsg
os.system('say -v Karen "'+str(themsg)+'"')
print("MyTTS Server 1.5 w/ MQTT starting up")
"""os.system('say -v Karen "TTS Server 1.5 Starting up!"')
say_message("TTS Server 1.5 Starting up!")
interrupted = False
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("", 1883, 60)
while True:
if interrupted:
  print "TTS Server is shutting down"

The python library for communicating with a MQTT server is called pahomqtt and you can install it via pip. The next thing you notice is that I imported signal class. I want to use signal to catch a Ctrl-C (or signal from OS) and shut down the server gracefully. The on_connect function deals with subscribing to the correct message queue to receive messages from.. in this case “myTTS/message”. The on_message takes a message that was put in the message queue and uses the system function to call say with the message. The main body of the server takes care of starting the mqtt client and starting a loop to listen for messages.

I used mosquitto for my MQTT server. It came as a package for Centos 7, so it was easy to install. You can also find it here with setup instructions:

Next time I’ll show another python app that put random messages (like the time) in the queue for the TTS server to say.

Leave a Reply