#ifndef PULSEAUDIO_H #define PULSEAUDIO_H #include #include #include #include "exception.h" #include /** * receive events from pulse audio */ class PulseAudio { private: pa_sample_spec sampleSpec; pa_simple* simple; std::thread thread; public: /** ctor */ PulseAudio() { sampleSpec.format = PA_SAMPLE_S16LE; sampleSpec.rate = 44100; sampleSpec.channels = 1; // pactl list | grep "\.monitor" const char* server = nullptr; const char* clientName = "beat detection"; const char* streamName = "recording beats"; const char* dev = "alsa_output.pci-0000_00_1b.0.analog-stereo.monitor"; //nullptr; //const char* dev = "alsa_output.usb-0d8c_USB_Sound_Device-00-Device.analog-surround-51.monitor"; // connect int error; simple = pa_simple_new(server, clientName, PA_STREAM_RECORD, dev, streamName, &sampleSpec, NULL, NULL, &error); if (!simple) {throw Exception("error while connecting to PulseAudio");} std::cout << simple << std::endl; } void start() { std::cout << "starting read loop" << std::endl; thread = std::thread(&PulseAudio::readLoop, this); } void join() { thread.join(); } void read(int16_t* dst, int samples) { const int bytes = samples * sizeof(int16_t); int error; const int res = pa_simple_read(simple, dst, bytes, &error); if (res < 0) {throw Exception("error while reading data");} } private: void readLoop() { std::cout << "hello from read loop" << std::endl; int16_t buffer[1024]; int error = 0; while(true) { const int res = pa_simple_read(simple, buffer, sizeof(buffer), &error); std::cout << res << ", " << error << std::endl; if (res < 0) {throw Exception("error while reading data");} std::cout << buffer[0] << "," << buffer[1] << "," << buffer[2] << "," << buffer[3] << std::endl; } } /* int i = -1; while (!exit_program) { i = (i+1) % BUFNUMBER; pthread_mutex_lock(&(buffer[i].write)); // Record data and save it to the buffer if (pa_simple_read(s, buffer[i].buf, sizeof(buffer[i].buf), &error) < 0) { fprintf(stderr, __FILE__": pa_simple_read() failed: %s\n", pa_strerror(error)); pa_simple_free(s); exit(EXIT_FAILURE); } // unlock the reading mutex pthread_mutex_unlock(&(buffer[i].read)); // open up for reading } */ }; #endif // PULSEAUDIO_H