I have created a code to loop audio between the mic and speaker of a usb headset. I ran code on Axon Board where the latency was more than 1 second whereas when the same code is run on Raspberry Pi 5 I get 0.2second or less delay.
Attaching the code as follows.
/*
command to build
g++ -o pulse_loopback pulse_loopback.cpp -lpulse -lpulse-simple
To run the output
./pulse_loopback
find headset source sink names with
pacmd list-sources
pacmd list-sinks
*/
#include <stdio.h>
#include <unistd.h>
#include <pulse/simple.h>
#include <pulse/error.h>
#include <fstream>
#include <iostream>
#define BUFSIZE 100
int main(int argc, char *argv[])
{
// PulseAudio variables
pa_simple *source_stream = NULL;
pa_simple *sink_stream = NULL;
pa_sample_spec source_spec, sink_spec;
int error;
const char *source_device = "alsa_input.usb-Plantronics_Plantronics_Blackwire_3220_Series_834A0F341D35A841AEB199CC987380A8-00.analog-stereo";
const char *sink_device = "alsa_output.usb-Plantronics_Plantronics_Blackwire_3220_Series_834A0F341D35A841AEB199CC987380A8-00.analog-stereo";
// Create the source stream
source_spec.format = PA_SAMPLE_FLOAT32LE;
source_spec.channels = 1;
source_spec.rate = 8000;
if (!(source_stream = pa_simple_new(NULL, "PulseAudioExample", PA_STREAM_RECORD, source_device, "Record", &source_spec, NULL, NULL, &error)))
{
fprintf(stderr, "pa_simple_new() failed: %s\n", pa_strerror(error));
goto finish;
}
// Create the sink stream
sink_spec.format = PA_SAMPLE_FLOAT32LE;
sink_spec.channels = 1;
sink_spec.rate = 8000;
if (!(sink_stream = pa_simple_new(NULL, "PulseAudioExample", PA_STREAM_PLAYBACK, sink_device, "Playback", &sink_spec, NULL, NULL, &error)))
{
fprintf(stderr, "pa_simple_new() failed: %s\n", pa_strerror(error));
goto finish;
}
// Read from source and write to sink
uint8_t buf[BUFSIZE];
while (true)
{
// Read from source
if (pa_simple_read(source_stream, buf, sizeof(buf), &error) < 0)
{
fprintf(stderr, __FILE__ ": pa_simple_read() failed: %s\n", pa_strerror(error));
goto finish;
}
// Write to sink
if (pa_simple_write(sink_stream, buf, sizeof(buf), &error) < 0)
{
fprintf(stderr, __FILE__ ": pa_simple_write() failed: %s\n", pa_strerror(error));
goto finish;
}
}
// Cleanup
finish:
if (source_stream)
pa_simple_free(source_stream);
if (sink_stream)
pa_simple_free(sink_stream);
return 0;
}