From 083e46d5d23d2105e2df1adc769700fb579c9597 Mon Sep 17 00:00:00 2001 From: Roland Reichwein Date: Thu, 2 Jan 2025 13:14:08 +0100 Subject: Initial commit --- alsa.cpp | 114 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 alsa.cpp (limited to 'alsa.cpp') diff --git a/alsa.cpp b/alsa.cpp new file mode 100644 index 0000000..7df0805 --- /dev/null +++ b/alsa.cpp @@ -0,0 +1,114 @@ +#include + +#include + +#include +#include +#include +#include + +static const char *device = "default"; /* playback device */ +const snd_pcm_sframes_t nframes = 1024; // ~1/44th sec buffer size +int16_t buffer[nframes]; /* some random data */ +const unsigned int f_sample = 44100; +const double pi = std::acos(-1); + +class ClickStream +{ +private: + std::vector m_data; +public: + ClickStream() + { + std::string data_s = Reichwein::File::getFile("media/click.s16le"); + m_data.resize(data_s.size() / 2); + memcpy(m_data.data(), data_s.data(), data_s.size()); + } + +double generate(double phase) +{ + int i; + size_t j = phase; + + for (i = 0; i < nframes; i++) { + if (j >= m_data.size()) + j = 0; + buffer[i] = m_data[j]; + j++; + } + + return j; +} + +}; + +class PCM +{ +public: + PCM() + { + // non-blocking + if ((err = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) { + printf("Playback open error: %s\n", snd_strerror(err)); + exit(EXIT_FAILURE); + } + if ((err = snd_pcm_set_params(handle, + SND_PCM_FORMAT_S16_LE, + SND_PCM_ACCESS_RW_INTERLEAVED, + 1, + f_sample, + 1, + 20000)) < 0) { /* 0.5sec */ + printf("Playback open error: %s\n", snd_strerror(err)); + exit(EXIT_FAILURE); + } + + } + + ~PCM() + { + /* pass the remaining samples, otherwise they're dropped in close */ + err = snd_pcm_drain(handle); + if (err < 0) + printf("snd_pcm_drain failed: %s\n", snd_strerror(err)); + snd_pcm_close(handle); + } + + // write from buffer to ALSA PCM + bool write() + { + frames = snd_pcm_writei(handle, buffer, nframes); + if (frames < 0) { + std::cout << "Recovering." << std::endl; + frames = snd_pcm_recover(handle, frames, 0); + } + if (frames < 0) { + printf("snd_pcm_writei failed: %s\n", snd_strerror(frames)); + return false; + } + if (frames > 0 && frames < nframes) + printf("Short write (expected %li, wrote %li)\n", nframes, frames); + + return frames == 0; + } + +private: + int err; + snd_pcm_t *handle; + snd_pcm_sframes_t frames; +}; + +int main(void) +{ + PCM pcm; + + double phase = 0; + ClickStream stream; + for (unsigned int i = 0; i < 50; i++) { + phase = stream.generate(phase); + pcm.write(); + } + + return 0; +} + -- cgit v1.2.3