Repository navigation
Communication MQTT
MQTT is the publish/subscribe protocol of the IoT world: devices publish messages to a topic on a broker (e.g. Mosquitto), and every client that subscribed to the topic receives them. It is not made for continuous streams, but it is a simple way to deliver an audio clip - a recorded message, a sound file - to many devices, or to integrate audio into an existing MQTT setup (e.g. Home Assistant or Node-RED). See Communication for the general considerations.
There is no special class for MQTT: the ArduinoMqttClient library (available in the Library Manager) provides a MqttClient which is a Print while you write a message, so you can copy audio into it like into any other output.
From communication-mqtt-send.ino: publishes 100 KB of noise as one WAV message:
#include "WiFi.h"
#include "ArduinoMqttClient.h"
#include "AudioTools.h"
#define SIZE 1024
#define N 100
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
AudioInfo info(8000, 1, 16);
WhiteNoiseGenerator<int16_t> noise(32000);
GeneratedSoundStream<int16_t> in_stream(noise);
EncodedAudioStream out_stream(&mqttClient, new WAVEncoder()); // as WAV file
StreamCopy copier(out_stream, in_stream, SIZE);
void setup() {
// ... connect WiFi
mqttClient.setId("AudioTools"); // each client needs a unique id
if (!mqttClient.connect("test.mosquitto.org", 1883)) stop();
noise.begin(info);
in_stream.begin(info);
out_stream.begin(info); // writes the WAV header
mqttClient.beginMessage("audio.wav", SIZE * N, true); // topic, size, retain
copier.copyN(N); // N * SIZE bytes
mqttClient.endMessage();
}
void loop() {
mqttClient.poll(); // keep-alive for the broker
delay(1000);
}A subscriber gets the message in pieces from mqttClient.read() after parseMessage() - write them to a WAVDecoder/EncodedAudioStream and an output, or save them to a file. On a PC you can check the message with any MQTT client, e.g. mosquitto_sub -h test.mosquitto.org -t audio.wav -C 1 > audio.wav.
-
Message size: each message is kept by the broker in memory - many brokers limit the size (Mosquitto:
message_size_limit). Declare the size inbeginMessage()as in the example, so the client doesn't have to buffer the message. - Clips, not streams: for continuous live audio, UDP, TCP/IP or HTTP fit better. If you want to stream via MQTT anyway, send small messages (e.g. one codec frame each) and use a compressed format.
- Retain: with the retain flag the broker keeps the last message for clients that subscribe later.