spacebox/src/Audio.hpp

90 lines
2.0 KiB
C++

#ifndef Audio_h_
#define Audio_h_
#include <regex>
#include <map>
#include "SDL_mixer.h"
#include "filesystem.hpp"
#include "Node.hpp"
#include "Animation.hpp"
#include "extension.hpp"
struct BGM : Node
{
Mix_Music* music;
float volume = 1.0f;
BGM();
BGM(Node*);
BGM(Node*, const fs::path&);
BGM(const fs::path&);
void load_music(const fs::path&);
void set_volume(float);
void play(int = -1);
~BGM();
};
struct SoundEffect : Node
{
Mix_Chunk* chunk = nullptr;
int channel, loops = 0;
float volume = 1.0f;
Animation play_animation = Animation(&SoundEffect::play, this);
SoundEffect(Node*);
SoundEffect();
SoundEffect(Node*, const fs::path&);
SoundEffect(const fs::path&);
void load_chunk(const fs::path&);
void play(float);
void play();
void play_after(float);
void set_volume(float);
void set_loop_count(int);
void set_loop_forever();
bool is_playing(bool = false);
void update();
~SoundEffect();
};
struct Audio : Node
{
std::map<std::string, SoundEffect> sfx;
std::map<std::string, BGM> bgm;
Audio(Node*);
void load_sfx();
void load_bgm();
void update();
template <typename T>
void load_directory(const fs::path& root, std::map<std::string, T>& storage, Node* parent = nullptr)
{
SDL_Log("looking for audio files in %s", root.c_str());
if (fs::exists(root))
{
for (const fs::path& path : sb::glob(root / ".*"))
{
std::regex pattern("([^.]+).*$");
std::smatch match;
std::string basename = path.filename();
if (std::regex_match(basename, match, pattern))
{
std::string key = match[1].str();
SDL_Log("loading %s as %s", path.c_str(), key.c_str());
storage.try_emplace(key, parent, path);
}
}
}
}
};
#endif