Skip to content

Instantly share code, notes, and snippets.

@dakhnod
Last active November 28, 2024 15:17
Show Gist options
  • Select an option

  • Save dakhnod/95f06e65a68e4e4a408dd4ebccb351b5 to your computer and use it in GitHub Desktop.

Select an option

Save dakhnod/95f06e65a68e4e4a408dd4ebccb351b5 to your computer and use it in GitHub Desktop.
Pulse audio sine wave example

Sine wave player

This example demonstrates how to play a sine wave through Pulse audio. Keep in mind that this code does NOT do any error handling. This is about the minimal amount code needed to play a sine wave.

How to compile

sudo apt install libpulse-dev
gcc sine.c -o play -lm -lpulse-simple
#define _USE_MATH_DEFINES
#include <pulse/simple.h>
#include <math.h>
#define SAMPLE_SIZE 40000
int main(){
pa_simple *s;
pa_sample_spec ss;
ss.format = PA_SAMPLE_FLOAT32;
ss.channels = 1;
ss.rate = 44100;
s = pa_simple_new(
NULL, // Use the default server.
"sine player", // Our application's name.
PA_STREAM_PLAYBACK,
NULL, // Use the default device.
"Music", // Description of our stream.
&ss, // Our sample format.
NULL, // Use default channel map
NULL, // Use default buffering attributes.
NULL // Ignore error code.
);
float sin_datapoints[SAMPLE_SIZE];
for(int i = 0; i < SAMPLE_SIZE; i++){
float progress = M_PI * 2 * (i / 400.0);
sin_datapoints[i] = sin(progress);
}
for(int i = 0; i < 10; i++) {
pa_simple_write(s, sin_datapoints, sizeof(sin_datapoints), NULL);
}
pa_simple_drain(s, NULL);
pa_simple_free(s);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment