aboutsummaryrefslogtreecommitdiff
path: root/src/sdl/sounds.c
blob: 956229c7c36ad3574e3705791d66825131399d39 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <SDL.h>
#include "util.h"
#include "assets.h"
#include "sounds.h"

#define SOUND_OFS(asset_id) ((asset_id) - ASSET_SOUND_FIRST - 1)

void
sounds_init(
  Mix_Chunk ** const sounds
) {
  for (asset_id_t id = ASSET_SOUND_FIRST + 1; id < ASSET_SOUND_LAST; id++) {
    // get asset
    const asset_t * const asset = asset_get(id);

    // create rwops
    SDL_RWops *rw = SDL_RWFromConstMem(asset->buf, asset->len);
    if (!rw) {
      die("SDL_RWFromConstMem(): %s", SDL_GetError());
    }

    // load chunk
    Mix_Chunk *chunk = Mix_LoadWAV_RW(rw, 1);
    if (!chunk) {
      die("Mix_LoadWAV_RW(): %s", Mix_GetError());
    }

    // add to list of sounds
    sounds[SOUND_OFS(id)] = chunk;
  }
}

void
sound_play(
  Mix_Chunk ** const sounds,
  const asset_id_t id
) {
  // check ID
  if (id <= ASSET_SOUND_FIRST || id >= ASSET_SOUND_LAST) {
    die("invalid sound asset id: %u", id);
  }

  // play sound
  if (Mix_PlayChannel(-1, sounds[SOUND_OFS(id)], 0)) {
    die("Mix_PlayChannel(): %s", Mix_GetError());
  }
}