From d6badb97be4243ae633da3571527000bb87e5340 Mon Sep 17 00:00:00 2001 From: Alexander Kraus Date: Wed, 4 Jun 2025 15:44:31 +0200 Subject: [PATCH] feat(examples): added playback timestamp extraction to ALSA example. (#190) --- examples/code/C/cplay.unix.c | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/examples/code/C/cplay.unix.c b/examples/code/C/cplay.unix.c index 13d8b83..1207189 100644 --- a/examples/code/C/cplay.unix.c +++ b/examples/code/C/cplay.unix.c @@ -2,12 +2,17 @@ #include #include #include +#include #include "physics_girl_st.h" static SUsample sound_buffer[SU_LENGTH_IN_SAMPLES * SU_CHANNEL_COUNT]; static snd_pcm_t *pcm_handle; -static pthread_t render_thread; -static uint32_t render_thread_handle; +static pthread_t render_thread, playback_thread; +static uint32_t render_thread_handle, playback_thread_handle; + +void play() { + snd_pcm_writei(pcm_handle, sound_buffer, SU_LENGTH_IN_SAMPLES); +} int main(int argc, char **args) { // Unix does not have gm.dls, no need to ifdef and setup here. @@ -33,7 +38,21 @@ int main(int argc, char **args) { 0, SU_LENGTH_IN_SAMPLES ); - snd_pcm_writei(pcm_handle, sound_buffer, SU_LENGTH_IN_SAMPLES); + playback_thread_handle = pthread_create(&playback_thread, 0, (void *(*)(void *))play, 0); + + // This is for obtaining the playback time. + snd_pcm_status_t *status; + snd_pcm_status_malloc(&status); + snd_htimestamp_t htime, htstart; + snd_pcm_status(pcm_handle, status); + snd_pcm_status_get_htstamp(status, &htstart); + for(int sample; sample < SU_LENGTH_IN_SAMPLES; sample = (int)(((float)htime.tv_sec + (float)htime.tv_nsec * 1.e-9 - (float)htstart.tv_sec - (float)htstart.tv_nsec * 1.e-9) * SU_SAMPLE_RATE)) { + snd_pcm_status(pcm_handle, status); + snd_pcm_status_get_htstamp(status, &htime); + printf("Sample: %d\n", sample); + usleep(1000000 / 30); + } + snd_pcm_status_free(status); return 0; }