Bubba-3D  0.9.0
Awesome game engine!
AudioManager.cpp
1 /*
2  * This file is part of Bubba-3D.
3  *
4  * Bubba-3D is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * Bubba-3D is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public License
15  * along with Bubba-3D. If not, see http://www.gnu.org/licenses/.
16  */
17 //
18 // Created by johan on 2016-01-16.
19 //
20 
21 
22 #include "AudioManager.h"
23 #include <sstream>
24 #include <Logger.h>
25 
26 
27 std::map<std::string, sf::Music*> AudioManager::musics;
28 std::map<std::string, sf::SoundBuffer> AudioManager::soundBuffers;
29 
30 
31 sf::Sound* AudioManager::loadAndFetchSound(const std::string &fileName){
32  try {
33  return getSoundBuffer(fileName);
34  } catch (std::invalid_argument exception) {
35  loadSoundBuffer(fileName);
36  return getSoundBuffer(fileName);
37  }
38 }
39 
40 void AudioManager::loadSoundBuffer(const std::string &fileName) {
41  sf::SoundBuffer soundBuffer;
42  soundBuffer.loadFromFile(fileName);
43 
44  soundBuffers.insert(std::pair<std::string, sf::SoundBuffer>(fileName, soundBuffer));
45 }
46 
47 sf::Sound* AudioManager::getSoundBuffer(std::string fileName){
48  sf::SoundBuffer *soundBuffer = getItemFromMap(&soundBuffers, fileName);
49  sf::Sound *sound = new sf::Sound();
50  sound->setBuffer(*soundBuffer);
51  return sound;
52 }
53 
54 
55 sf::Music* AudioManager::loadAndFetchMusic(const std::string &fileName) {
56  try {
57  return getMusic(fileName);
58  } catch (std::invalid_argument exception) {
59  loadMusic(fileName);
60  return getMusic(fileName);
61  }
62 }
63 
64 void AudioManager::loadMusic(const std::string &fileName) {
65  sf::Music *music = new sf::Music();
66  music->openFromFile(fileName);
67 
68  musics.insert(std::pair<std::string, sf::Music*>(fileName, music));
69 }
70 
71 sf::Music* AudioManager::getMusic(std::string fileName) {
72  return *getItemFromMap(&musics, fileName);
73 }
74 
75 template<typename Type>
76 Type* AudioManager::getItemFromMap(std::map<std::string, Type> *map, std::string id) {
77  typename std::map<std::string, Type>::iterator it = map->find(id);
78  if( it != map->end()) {
79  return &it->second;
80  } else {
81  std::stringstream errorMessage;
82  errorMessage << id << " hasn't been loaded into AudioManager before fetched";
83  throw std::invalid_argument(errorMessage.str());
84  }
85 }
86 
87 
88 
89 
90 
91