2 #include <SDL2/SDL_mixer.h>
8 #include "sound_samples.h"
9 #include "system/error.h"
10 #include "system/log.h"
11 #include "system/lt.h"
12 #include "system/nth_alloc.h"
22 static int mix_get_free_channel(void)
24 for (int i = 0; i < MIX_CHANNELS; ++i) {
25 if (!Mix_Playing(i)) {
33 Sound_samples *create_sound_samples(const char *sample_files[],
34 size_t sample_files_count)
37 assert(sample_files_count > 0);
44 Sound_samples *sound_samples = PUSH_LT(lt, nth_alloc(sizeof(Sound_samples)), free);
45 if (sound_samples == NULL) {
46 throw_error(ERROR_TYPE_LIBC);
50 sound_samples->samples = PUSH_LT(
52 nth_alloc(sizeof(Mix_Chunk*) * sample_files_count),
54 if (sound_samples->samples == NULL) {
55 throw_error(ERROR_TYPE_LIBC);
59 for (size_t i = 0; i < sample_files_count; ++i) {
60 sound_samples->samples[i] = PUSH_LT(
62 Mix_LoadWAV(sample_files[i]),
64 if (sound_samples->samples[i] == NULL) {
65 throw_error(ERROR_TYPE_SDL2_MIXER);
70 sound_samples->samples_count = sample_files_count;
71 sound_samples->paused = 0;
73 sound_samples->lt = lt;
78 void destroy_sound_samples(Sound_samples *sound_samples)
80 assert(sound_samples);
81 RETURN_LT0(sound_samples->lt);
84 int sound_samples_play_sound(Sound_samples *sound_samples,
88 assert(sound_samples);
90 if (sound_index < sound_samples->samples_count) {
91 const int free_channel = mix_get_free_channel();
93 log_info("Found free channel: %d\n", free_channel);
95 if (free_channel >= 0) {
96 return Mix_PlayChannel(free_channel, sound_samples->samples[sound_index], loops);
103 int sound_samples_toggle_pause(Sound_samples *sound_samples)
105 assert(sound_samples);
107 if (sound_samples->paused) {
113 sound_samples->paused = !sound_samples->paused;