playground-sdk/audio/audio.h

61 lines
2 KiB
C++

#pragma once
#include "audio/cadi_bank.h"
#include "core/vfs.h"
#include <cstdint>
#include <memory>
#include <span>
#include <string>
#include <string_view>
#include <vector>
struct SDL_AudioStream;
namespace playground {
struct DecodedSound {
int channels = 0;
int sampleRate = 0;
std::vector<int16_t> samples; // interleaved signed 16-bit PCM
};
// The bundled sound files are Ogg Vorbis. Decode without needing an audio device.
bool decodeOgg(std::span<const uint8_t> bytes, DecodedSound& sound,
std::string* error = nullptr);
// Independent playback lanes let music continue while sound effects play.
class Audio {
public:
explicit Audio(const Vfs& assets, const Vfs* looseAssets = nullptr)
: assets_(assets), looseAssets_(looseAssets) {}
~Audio();
Audio(const Audio&) = delete;
Audio& operator=(const Audio&) = delete;
bool playAsset(std::string_view path, std::string* error = nullptr);
bool playEvent(std::string_view event, std::string* error = nullptr);
void setCadiBankPath(std::string path) { bankPath_ = std::move(path); bank_.reset(); bankAttempted_ = false; }
void stop();
bool active() const;
bool musicActive() const { return music_.stream != nullptr; }
bool sfxActive() const { return sfx_.stream != nullptr; }
bool environmentActive() const { return environment_.stream != nullptr; }
private:
struct Lane {
SDL_AudioStream* stream = nullptr;
std::vector<int16_t> pcm;
bool loop = false;
};
bool playEncoded(std::span<const uint8_t> bytes, Lane& lane, bool loop, std::string* error);
static void feedLoop(void* userdata, SDL_AudioStream* stream, int additional, int total);
static void stopLane(Lane& lane);
const Vfs& assets_;
const Vfs* looseAssets_ = nullptr;
std::unique_ptr<CadiBank> bank_;
bool bankAttempted_ = false;
std::string bankPath_;
Lane music_, sfx_, environment_;
bool initialized_ = false;
};
} // namespace playground