In my Arduino AudioTools project I am providing many examples that show how to distribute audio over the network.
One scenario that is easy to implement, is to write the data via http post. On the server side usually one of the following options is expected:
- the content length and we can just write the audio data to the stream after the http header
- no content length, adding transfer-encoding: chunked to the post header and writing in chunked format.
Arduino Sketch
Here is the corresponding Arduino Sketch that posts the audio data in chunked mode:
#include "AudioTools.h"
const char *ssid = "your SSID";
const char *password = "your PASSWORD";
const char *url_str = "http://192.168.1.44:9988";
AudioInfo info(44100, 2, 16);
SineWaveGenerator<int16_t> sineWave(32000);
GeneratedSoundStream<int16_t> sound(sineWave);
WiFiClient client;
HttpRequest http(client);
StreamCopy copier(http, sound); // copy kit to kit
void startWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println();
Serial.println(WiFi.localIP());
}
// Arduino Setup
void setup(void) {
// Open Serial
Serial.begin(115200);
AudioToolsLogger.begin(Serial, AudioToolsLogLevel::Info);
startWiFi();
// Setup sine wave
sineWave.begin(info, N_B4);
// start post
Url url(url_str);
http.header().put(TRANSFER_ENCODING, CHUNKED); // uncomment if chunked
if (!http.processBegin(POST, url, "audio/pcm")){
Serial.println("post failed");
stop();
}
}
// Arduino loop - copy sound to out
void loop() {
// posting the data
if (copier.copy() == 0) {
// closing the post
http.processEnd();
}
}
The logic is the following:
- we initialize
- the wifi
- the sine generator
- we submit the post by makeing sure that the request header contains transfer-encoding: chunked.
- finally we can just copy the sound data from the generator to http which automatically calls the chunked writes.
The (potentially updated) sketch can be found in the examples folder of the project
The Python Server
Here is a simple example server in python that shows how to process the chunked data.
2 Comments
nilesh · 17. December 2024 at 11:55
Regarding audio via http post , How we can use different than “http://192.168.1.44:9988”; as this hard coded not work with on our WIFI
pschatzmann · 17. December 2024 at 12:02
I thought it would be quite obvious, that you would need to replace this with the address of the machine where your server is running!