]> git.lizzy.rs Git - nothing.git/blob - src/sound_sample.c
(#132) Play sample
[nothing.git] / src / sound_sample.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <assert.h>
4
5 #include <SDL2/SDL.h>
6 #include <SDL2/SDL_mixer.h>
7
8 #include "./lt.h"
9 #include "./sound_sample.h"
10 #include "./error.h"
11
12 struct sound_sample_t
13 {
14     lt_t *lt;
15     Mix_Chunk *chunk;
16 };
17
18 sound_sample_t *create_sound_sample_from_file(const char *filepath)
19 {
20     assert(filepath);
21
22     lt_t *lt = create_lt();
23     if (lt == NULL) {
24         return NULL;
25     }
26
27     sound_sample_t *sound_sample = PUSH_LT(lt, malloc(sizeof(sound_sample_t)), free);
28     if (sound_sample == NULL) {
29         throw_error(ERROR_TYPE_LIBC);
30         RETURN_LT(lt, NULL);
31     }
32
33     sound_sample->chunk = PUSH_LT(lt, Mix_LoadWAV(filepath), Mix_FreeChunk);
34     if (sound_sample->chunk == NULL) {
35         throw_error(ERROR_TYPE_SDL2_MIXER);
36         RETURN_LT(lt, NULL);
37     }
38
39     sound_sample->lt = lt;
40
41     return sound_sample;
42 }
43
44 void destroy_sound_sample(sound_sample_t *sound_sample)
45 {
46     assert(sound_sample);
47     RETURN_LT0(sound_sample->lt);
48 }
49
50 int sound_sample_play(sound_sample_t *sound_sample, int channel)
51 {
52     assert(sound_sample);
53     return Mix_PlayChannel(channel, sound_sample->chunk, 1);
54 }