2 #include <SDL2/SDL_mixer.h>
8 #include "sound_samples.h"
9 #include "system/error.h"
10 #include "system/lt.h"
20 static int mix_get_free_channel(void)
22 for (int i = 0; i < MIX_CHANNELS; ++i) {
23 if (!Mix_Playing(i)) {
31 Sound_samples *create_sound_samples(const char *sample_files[],
32 size_t sample_files_count)
35 assert(sample_files_count > 0);
42 Sound_samples *sound_samples = PUSH_LT(lt, malloc(sizeof(Sound_samples)), free);
43 if (sound_samples == NULL) {
44 throw_error(ERROR_TYPE_LIBC);
48 sound_samples->samples = PUSH_LT(
50 malloc(sizeof(Mix_Chunk*) * sample_files_count),
52 if (sound_samples->samples == NULL) {
53 throw_error(ERROR_TYPE_LIBC);
57 for (size_t i = 0; i < sample_files_count; ++i) {
58 sound_samples->samples[i] = PUSH_LT(
60 Mix_LoadWAV(sample_files[i]),
62 if (sound_samples->samples[i] == NULL) {
63 throw_error(ERROR_TYPE_SDL2_MIXER);
68 sound_samples->samples_count = sample_files_count;
69 sound_samples->paused = 0;
71 sound_samples->lt = lt;
76 void destroy_sound_samples(Sound_samples *sound_samples)
78 assert(sound_samples);
79 RETURN_LT0(sound_samples->lt);
82 int sound_samples_play_sound(Sound_samples *sound_samples,
86 assert(sound_samples);
88 if (sound_index < sound_samples->samples_count) {
89 const int free_channel = mix_get_free_channel();
91 printf("Found free channel: %d\n", free_channel);
93 if (free_channel >= 0) {
94 return Mix_PlayChannel(free_channel, sound_samples->samples[sound_index], loops);
101 int sound_samples_toggle_pause(Sound_samples *sound_samples)
103 assert(sound_samples);
105 if (sound_samples->paused) {
111 sound_samples->paused = !sound_samples->paused;