-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAudioEngine.cpp
More file actions
119 lines (91 loc) · 2.16 KB
/
Copy pathAudioEngine.cpp
File metadata and controls
119 lines (91 loc) · 2.16 KB
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
110
111
112
113
114
115
116
117
118
119
#include "AudioEngine.h"
#include "Errors.h"
namespace KlaoudeEngine
{
void SoundEffect::play(int loops)
{
if(Mix_PlayChannel(-1, m_chunk, loops) == -1)
fatalError("Mix_PlayChannel error: " + std::string(Mix_GetError()));
}
void Music::play(int loops)
{
if(Mix_PlayMusic(m_music, loops) == -1)
fatalError("Mix_PlayMusic error: " + std::string(Mix_GetError()));
}
void Music::pause()
{
Mix_PauseMusic();
}
void Music::stop()
{
Mix_HaltMusic();
}
void Music::resume()
{
Mix_ResumeMusic();
}
AudioEngine::AudioEngine()
{
}
AudioEngine::~AudioEngine()
{
destroy();
}
void AudioEngine::init()
{
if (m_isInit)
fatalError("Tried to init audio engine twice !");
if (Mix_Init(MIX_INIT_OGG | MIX_INIT_FLAC | MIX_INIT_MOD | MIX_INIT_MP3) == -1)
fatalError("Mix_Init error: " + std::string(Mix_GetError()));
if(Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 1024) == -1)
fatalError("Mix_OpenAudio error: " + std::string(Mix_GetError()));
m_isInit = true;
}
void AudioEngine::destroy()
{
if(m_isInit)
{
m_isInit = false;
for (auto& it : m_effectMap)
Mix_FreeChunk(it.second);
for (auto& it : m_musicMap)
Mix_FreeMusic(it.second);
m_effectMap.clear();
m_musicMap.clear();
Mix_CloseAudio();
Mix_Quit();
}
}
SoundEffect AudioEngine::loadSoundEffect(const std::string & filePath)
{
auto it = m_effectMap.find(filePath);
SoundEffect effect;
if (it == m_effectMap.end())
{
Mix_Chunk* chunk = Mix_LoadWAV(filePath.c_str());
if (chunk == nullptr)
fatalError("Mix_LoadWAV error: " + std::string(Mix_GetError()));
effect.m_chunk = chunk;
m_effectMap[filePath] = chunk;
}
else
effect.m_chunk = it->second;
return effect;
}
Music AudioEngine::loadMusic(const std::string & filePath)
{
auto it = m_musicMap.find(filePath);
Music music;
if (it == m_musicMap.end())
{
Mix_Music* mixMusic = Mix_LoadMUS(filePath.c_str());
if (mixMusic == nullptr)
fatalError("Mix_LoadMUS error: " + std::string(Mix_GetError()));
music.m_music = mixMusic;
m_musicMap[filePath] = mixMusic;
}
else
music.m_music = it->second;
return music;
}
}