2 #include <SDL2/SDL_mixer.h>
3 #include "system/stacktrace.h"
8 #include "sound_samples.h"
9 #include "system/log.h"
10 #include "system/lt.h"
11 #include "system/nth_alloc.h"
21 static int mix_get_free_channel(void)
23 for (int i = 0; i < MIX_CHANNELS; ++i) {
24 if (!Mix_Playing(i)) {
32 Sound_samples *create_sound_samples(const char *sample_files[],
33 size_t sample_files_count)
35 trace_assert(sample_files);
36 trace_assert(sample_files_count > 0);
43 Sound_samples *sound_samples = PUSH_LT(lt, nth_calloc(1, sizeof(Sound_samples)), free);
44 if (sound_samples == NULL) {
48 sound_samples->samples = PUSH_LT(
50 nth_calloc(1, sizeof(Mix_Chunk*) * sample_files_count),
52 if (sound_samples->samples == NULL) {
56 for (size_t i = 0; i < sample_files_count; ++i) {
57 sound_samples->samples[i] = PUSH_LT(
59 Mix_LoadWAV(sample_files[i]),
61 if (sound_samples->samples[i] == NULL) {
62 log_fail("Could not load '%s': %s\n", sample_files[i], Mix_GetError());
67 sound_samples->samples_count = sample_files_count;
68 sound_samples->paused = 0;
70 sound_samples->lt = lt;
75 void destroy_sound_samples(Sound_samples *sound_samples)
77 trace_assert(sound_samples);
78 RETURN_LT0(sound_samples->lt);
81 int sound_samples_play_sound(Sound_samples *sound_samples,
85 trace_assert(sound_samples);
87 if (sound_index < sound_samples->samples_count) {
88 const int free_channel = mix_get_free_channel();
90 log_info("Found free channel: %d\n", free_channel);
92 if (free_channel >= 0) {
93 return Mix_PlayChannel(free_channel, sound_samples->samples[sound_index], loops);
100 int sound_samples_toggle_pause(Sound_samples *sound_samples)
102 trace_assert(sound_samples);
104 if (sound_samples->paused) {
110 sound_samples->paused = !sound_samples->paused;