summary refs log tree commit diff stats
path: root/src/mixer.h
blob: b049118632cfd8d3fa961686ee3b7b28ff4f7ff4 (plain) (blame)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#ifndef MIXER_H_6DF82000
#define MIXER_H_6DF82000

#include <SDL_mixer.h>
#include <memory>
#include <stdexcept>
#include <map>
#include <string>

class mix_error : public std::logic_error {
public:

  mix_error() : std::logic_error(Mix_GetError())
  {
  }
};

class mix_wrapper {
public:

  mix_wrapper()
  {
    if (Mix_Init(0) != 0) {
      mix_error ex;
      Mix_Quit();

    	throw ex;
    }

    if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 1024) != 0) {
      mix_error ex;
      Mix_Quit();

    	throw ex;
    }
  }

  ~mix_wrapper()
  {
    Mix_CloseAudio();
    Mix_Quit();
  }
};

class chunk_deleter {
public:

  void operator()(Mix_Chunk* chunk) {
    Mix_FreeChunk(chunk);
  }
};

using chunk_ptr = std::unique_ptr<Mix_Chunk, chunk_deleter>;

class music_deleter {
public:

  void operator()(Mix_Music* music) {
    Mix_FreeMusic(music);
  }
};

using music_ptr = std::unique_ptr<Mix_Music, music_deleter>;

// MUST create the Renderer first!
class Mixer {
public:

  void playSound(std::string_view filename);

  int loopSound(std::string_view filename);

  void stopChannel(int channel);

  // name is the name of the file, not containing the extension
  // ms is the time in milliseconds to fade in
  void playMusic(std::string_view name, int ms = 0);

  bool isPlayingMusic() const { return !playingTrack_.empty(); }

  const std::string& getPlayingTrack() const { return playingTrack_; }

  void fadeoutMusic(int ms);

  void muteMusic();

  void unmuteMusic();

  bool isMusicMuted() const { return musicMuted_; }

  void pauseMusic();

  void unpauseMusic();

private:

  Mix_Chunk* getChunkByFilename(std::string filename);

  Mix_Music* getMusicByName(std::string_view name);

  mix_wrapper mix_;
  std::map<std::string, chunk_ptr> sounds_;
  std::map<std::string, music_ptr> music_;
  std::string playingTrack_;
  int musicVolume_ = MIX_MAX_VOLUME;
  bool musicMuted_ = false;
};

#endif /* end of include guard: MIXER_H_6DF82000 */