commit 14d3d89dd20b1ce52b9eb7b84584243e63f5e9a8
parent 8a7c022626e1301f9d7420d964075fceadd0a638
Author: Henry Wilson <henry@henryandlizzy.uk>
Date: Thu, 21 Apr 2022 23:53:24 +0100
gl-asteroids: Add sound to asteroids
Diffstat:
2 files changed, 36 insertions(+), 1 deletion(-)
diff --git a/makefile b/makefile
@@ -18,7 +18,7 @@ clean:
$(RM) $(c_targets) $(cpp_targets)
aio: -lrt
-gl-asteroids: -lglfw -lGL -lm
+gl-asteroids: -lglfw -lGL -lm -lasound
io_uring: -luring
pulse-async-client: -lpulse
pulse-simple-client: -lpulse-simple -lm
diff --git a/src/gl-asteroids.cpp b/src/gl-asteroids.cpp
@@ -1,4 +1,5 @@
#include <GLFW/glfw3.h>
+#include <alsa/asoundlib.h>
#include <cmath>
#include <vector>
#include <span>
@@ -10,6 +11,34 @@
#include <chrono>
#include <optional>
#include <functional>
+#include <atomic>
+
+std::atomic_flag beep;
+
+void sound_routine(std::stop_token token)
+{
+ snd_pcm_t* handle;
+
+ snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, 0);
+ snd_pcm_set_params(handle, SND_PCM_FORMAT_S16, SND_PCM_ACCESS_RW_INTERLEAVED, 1, 48000, 1, 10000);
+
+ while (not token.stop_requested())
+ {
+ std::array<short, 2048> buf;
+ if (beep.test())
+ {
+ beep.clear();
+ for (unsigned i = 0; i < buf.size(); ++i)
+ buf[i] = (i % 256 - 128) * 50;
+ }
+ else
+ for (auto& s : buf)
+ s = 0;
+ snd_pcm_sframes_t frames = snd_pcm_writei(handle, buf.data(), buf.size());
+ }
+ snd_pcm_drain(handle);
+ snd_pcm_close(handle);
+}
struct coord
{
@@ -328,6 +357,8 @@ int main(int argc, char* argv[])
for (auto& c : starsv)
c.x = dis_p(gen), c.y = dis_p(gen);
+ std::jthread sound(sound_routine);
+
while (!glfwWindowShouldClose(w) && not is_pressed(GLFW_KEY_ESCAPE))
{
float t = glfwGetTime();
@@ -401,6 +432,7 @@ int main(int argc, char* argv[])
if (is_pressed(GLFW_KEY_SPACE) && bullet_time < t && ammo)
{
+ beep.test_and_set();
--ammo;
bullet_time = t + 1/firerate;
@@ -454,6 +486,7 @@ int main(int argc, char* argv[])
{
if (is_colliding(r->p, b->p))
{
+ beep.test_and_set();
for (unsigned j = 0; j < 7; ++j)
{
entity debris = *r;
@@ -506,6 +539,8 @@ int main(int argc, char* argv[])
if (not is_colliding(b->p, powerups->p))
continue;
+ beep.test_and_set();
+
for (unsigned j = 0; j < 4; ++j)
{
entity debris = *powerups;