I want to sample audio as a learning process.
In the future i want to make my dorbell "smart" and stream the audio via VoIP. But as beginning i want to sample a simple audio signal from my laptop (e.g. simple sign wave) and send it via UDP over the network and listen to it.
As board i want to use a ESP32-12. Since i never had to sample a analog audio, i want to know if this code is "ok". I know its just software based and has the potential to be inprecise due to the lack of interrupts, but as said, its for the purpose of learning.
#include <WiFi.h>
#include <WiFiUdp.h>
// network setuf
#define WIFI_SSID "YOUR WIFI NETWORK SSID"
#define WIFI_PASS "YOUR WIFI PASSWORD"
const char *udpAddress = "192.168.1.100";
const int udpPort = 4210;
const int analogIn = A0;
const int sampleRate = 8000;
int samples[sampleRate];
int sampleIndex = 0;
int timerLastSample;
WiFiUDP UDP;
void setup()
{
// setup serial
Serial.begin(115200);
// give some time for serial connection
delay(1000);
// feedback
Serial.println("Connect to wifi...");
// connect to wifi
WiFi.begin(WIFI_SSID, WIFI_PASS);
// wait for wifi connection
while (WiFi.status() != WL_CONNECTED)
{
delay(100);
Serial.print(".");
}
}
void loop()
{
int now = micros();
if (now - timerLastSample >= (1 / sampleRate) * 1000)
{
timerLastSample = now;
samples[sampleIndex] = analogRead(analogIn);
sampleIndex += 1;
}
if (sampleIndex == sampleRate)
{
// reset
sampleIndex = 0;
// send data
UDP.beginPacket(udpAddress, udpPort);
UDP.write(samples);
UDP.endPacket();
}
}
```