Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdint.h>
- #include <unistd.h>
- #include <pulse/simple.h>
- #include <pulse/error.h>
- #include <chrono>
- constexpr int s_sample_rate = 48000;
- constexpr int s_sample_num = 256;
- int main()
- {
- printf("Running low-latency audio stream on PulseAudio Simple API...\n");
- struct pa_sample_spec ss;
- ss.rate = s_sample_rate;
- ss.format = PA_SAMPLE_FLOAT32LE;
- ss.channels = 2;
- struct pa_simple *pa;
- pa = pa_simple_new(NULL, "pulsefail", PA_STREAM_PLAYBACK, NULL, "GAME", &ss, NULL, NULL, NULL);
- if (!pa)
- {
- fprintf(stderr, "pa_simple_new() failed\n");
- return 1;
- }
- float src[2 * s_sample_num];
- for (int i = 0; i < 2 * s_sample_num; i++)
- {
- src[i] = i & 128 ? -0.1f : 0.1f;
- }
- long long counter = 0;
- auto start = std::chrono::steady_clock::now();
- while (true)
- {
- auto _now = std::chrono::steady_clock::now();
- if (_now - start >= std::chrono::seconds{10})
- {
- break;
- }
- auto expected_time = counter * s_sample_num * 1000000 / s_sample_rate;
- auto current_time = std::chrono::duration_cast<std::chrono::microseconds>(_now - start).count();
- if (expected_time > current_time)
- {
- usleep(expected_time - current_time);
- continue;
- }
- if (pa_simple_write(pa, src, sizeof(src), NULL) < 0)
- {
- fprintf(stderr, "pa_simple_write() failed\n");
- break;
- }
- counter++;
- }
- pa_simple_drain(pa, NULL);
- auto end = std::chrono::steady_clock::now();
- auto sec = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / 1000000.;
- printf("Stream finished: %fs, %d/%d: %lld samples.\n", sec, s_sample_rate, s_sample_num, counter);
- pa_simple_free(pa);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement