Skip to content

Instantly share code, notes, and snippets.

@dlandahl
Created February 7, 2020 22:38
Show Gist options
  • Save dlandahl/d8a0a671a3e819837fac5bcd85850bd5 to your computer and use it in GitHub Desktop.
Save dlandahl/d8a0a671a3e819837fac5bcd85850bd5 to your computer and use it in GitHub Desktop.
Generate tone with alsa
#include <cmath>
#include <random>
#include <iostream>
#include "alsa/asoundlib.h"
unsigned const size = 1024;
unsigned const rate = 44100;
float const circle = 6.28318530;
inline void do_audio(float* out)
{
static float phase = 0.f;
static const float frequency = 440.f;
*out = std::sin(phase * circle);
phase += frequency / rate;
if (phase >= 1.f) phase -= 1.f;
}
int main()
{
snd_pcm_t *ostream;
snd_pcm_hw_params_t *oparams;
snd_pcm_open(&ostream, "default", SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC);
snd_pcm_hw_params_alloca ( &oparams );
snd_pcm_hw_params_any(ostream, oparams);
snd_pcm_hw_params_set_format(ostream, oparams, SND_PCM_FORMAT_FLOAT_LE);
snd_pcm_hw_params_set_rate(ostream, oparams, rate, 0);
snd_pcm_hw_params(ostream, oparams);
float odata[size] = {0};
while (true)
{
for (unsigned n = 0; n < size; n++) do_audio(&odata[n]);
snd_pcm_writei(ostream, odata, size);
}
snd_pcm_drain(ostream);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment