Site icon High Voltages

Audio files using MQTT protocol

Audio files using MQTT protocol
Audio files using MQTT protocol

In this article, you will learn how you can publish and subscribe Audio files using MQTT protcol.

Firstly, If you are new to MQTT protcol, you should read what is MQTT protocol, What are MQTT topics and How MQTT publish subscribe model works. If you are familiar with these topics, then I will suggest you to read this article, How to use MQTT protcol in Python.

Okay, If you have read all those topics or you were already familiar with all these topics, you are ready for next step. MQTT protocol is capable of sending upto 256MB of data in payload and its applications of MQTT is not only limited to text messages, but also we can send Images using MQTT protocol and send audio files using MQTT protocol, which we are going to do in this tutorial.

Publishing Audio files using MQTT protocol

Publishing Audio files using MQTT protocol is very straightforward, The methodology is same as what we followed in the sending Images using MQTT protcol, However the following image explains it.

Audio files using MQTT protocol
Publishing Audio files using MQTT protocol

The first thing is to read the audio file, I am using sample .mp3 files from here for testing.

with open("./sample.mp3",'rb') as file:
    filecontent = file.read()

Then, once the file is read, we need to convert our audio files into byte array.

    byteArr = bytearray(filecontent)

and then we will get a byte array is byteArr variable, we will publish that byteArr to topic “Audios”.

    result = client.publish(topic,byteArr,2)
msg_status = result[0]
if msg_status == 0:
    print(f"message : Message sent to topic {topic}")
else:
    print(f"Failed to send message to topic {topic}")

And the audio file will be published in the form of byte array to the topic. Following code is used to publish the audio files using MQTT protocol.

import time
from paho.mqtt import client as mqtt_client

broker = 'broker.hivemq.com'
port = 1883
topic = "audios"
client_id = 'your client id'

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Successfully connected to MQTT broker")
        else:
            print("Failed to connect, return code %d", rc)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def publish(client):
    with open("./sample.mp3",'rb') as file:

        filecontent = file.read()
        byteArr = bytearray(filecontent)
        print(byteArr)
        result = client.publish(topic,byteArr,2)
    msg_status = result[0]
    if msg_status == 0:
        print(f"message sent to topic {topic}")
    else:
        print(f"Failed to send message to topic {topic}")

def main():
    client = connect_mqtt()
    client.loop_start()
    publish(client)
    time.sleep(5)
    client.loop_stop()


if __name__ == '__main__':
    main()

The code uses the paho-mqtt library, therefore, you need to install it before running this code in python terminal or ide. You can install paho-mqtt library using the pip as following,

pip3 install paho-mqtt

The above code is using hivemq free public mqtt broker, and there are several functions such as connect_mqtt which we are using for connecting to mqtt broker and publish function which is helping us to send our mp3 or audio files using mqtt protocol. Since the same code is used for sending images on mqtt protocol, I have explained this code in previous blog, therefore I am not going into the details of the code.

Receive Audio files using MQTT protcol

For recieving the audio files or our sample.mp3 file using mqtt protocol, we will decode the byte array to audio file. The concept is similar but it will be reversed. So whenever we will recieve a message on topic audios, we will decode it to audio file. Remember the message will be in bytes not the actual audio. Therefore, firstly , we will create an empty file receive.mp3 file.

f = open('receive.mp3', 'wb')

and then we will read write the byte array to the file and it will be converted to the actual audio file that we sent from the publishing client.

f.write(msg.payload)
f.close()

The following code is used to subscribe to a topic, recieve byte array and then decode it to the audio file.

from paho.mqtt import client as mqtt_client

broker = 'broker.hivemq.com'
port = 1883
topic = "photos"
topic_sub = "audios"
client_id = 'xzcfghjt123'

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Successfully connected to MQTT broker")
        else:
            print("Failed to connect, return code %d", rc)
    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        f = open('receive.mp3', 'wb')
        f.write(msg.payload)
        f.close()
        print ('Audio received')

    client.subscribe(topic_sub)
    client.on_message = on_message

def main():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()
    
if __name__ == '__main__':
    main()

This code has some same function as the publishing code , but here we have a subscribe function in which when we are getting a message, we are creating a mp3 file and writing our bytearray data that is coming from the publishing client.

Conclusion

I hope this tutorial helps you understand, how you can send audio using MQTT protocol. If you do so, also check how to create MQTT dashboard using python, that can help you create a nice GUI and with a bit of extra effort, you can upload and receive audios using the GUI. Or if you want to create a web based dashboard or android dashboard, don’t worry I have got you covered, this tutorial will help you create a web dashboard for MQTT.
All these tutorials can help you build your own Chat application, which i will try to cover in the next articles.

Exit mobile version