From 359b503ecc7c584bacda044a9cbe3c12f8da839c Mon Sep 17 00:00:00 2001 From: quou Date: Tue, 24 Sep 2024 20:30:27 +1000 Subject: audio --- plat.c | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) (limited to 'plat.c') diff --git a/plat.c b/plat.c index 2101910..e178137 100644 --- a/plat.c +++ b/plat.c @@ -427,3 +427,101 @@ void app_end(App* a) { } #endif + + +#ifdef plat_pulse +#include "maths.h" +#define inline /* erm sir we are using C90 here... */ +#include +#include +#include +#include + +struct { + short* buf; + pa_simple* dev; + int r, play, time; + pthread_t worker; + pthread_mutex_t mutex; +} audio; + +void* audio_worker(void* arg) { + const int s = audio_buffer_size; + int i, c = 1; + short* buf = audio.buf; + pa_simple* dev = audio.dev; + (void)arg; + while (c) { + pthread_mutex_lock(&audio.mutex); + if (!audio.r) c = 0; + for ( + i = 0; + i < s && audio.play; + i++, audio.play--, audio.time++ + ) buf[i] = (short)(sin((double)audio.time / 0.05) * 16000.0); + pthread_mutex_unlock(&audio.mutex); + for (; i < s; i++) { + buf[i] = 0; + } + pa_simple_write(dev, buf, s * sizeof(short), 0); + } + return 0; +} + +void init_audio(void) { + pa_sample_spec sp = { 0 }; + sp.format = PA_SAMPLE_S16LE; + sp.channels = 1; + sp.rate = audio_sample_rate; + audio.dev = pa_simple_new( + 0, + game_name, + PA_STREAM_PLAYBACK, + 0, + "Game Audio", + &sp, + 0, + 0, + 0 + ); + audio.r = 0; + audio.play = 0; + if (!audio.dev) { + print_err("Failed to create audio device.\n"); + print_war("Running without audio.\n"); + return; + } + audio.r = 1; + audio.buf = malloc( + audio_buffer_size * + sizeof *audio.buf + ); + pthread_mutex_init(&audio.mutex, 0); + pthread_create( + &audio.worker, + 0, + audio_worker, + 0 + ); +} + +void deinit_audio(void) { + if (audio.dev) { + pthread_mutex_lock(&audio.mutex); + audio.r = 0; + pthread_mutex_unlock(&audio.mutex); + pthread_mutex_destroy(&audio.mutex); + pthread_join(audio.worker, 0); + pa_simple_drain(audio.dev, 0); + pa_simple_free(audio.dev); + free(audio.buf); + } +} + +void play_sound(int len) { + pthread_mutex_lock(&audio.mutex); + audio.play += len; + pthread_mutex_unlock(&audio.mutex); +} + +#endif -- cgit v1.2.3-54-g00ecf