74 lines
1.5 KiB
C++
74 lines
1.5 KiB
C++
#pragma once
|
|
|
|
#include "Component.hpp"
|
|
#include "raylib-cpp.hpp"
|
|
|
|
#include <algorithm>
|
|
#include <string>
|
|
|
|
/**
|
|
* Lightweight component that owns a raylib::Sound instance.
|
|
* The component exposes a simple API so other gameplay systems can trigger the
|
|
* sound without having to track the resource themselves.
|
|
*/
|
|
struct AudioComponent : public Component {
|
|
std::string filePath;
|
|
bool playOnStart = false;
|
|
float volume = 1.0f;
|
|
|
|
void Setup() override {
|
|
if (!filePath.empty()) {
|
|
Load(filePath);
|
|
}
|
|
}
|
|
|
|
void Update(float) override {}
|
|
|
|
void Cleanup() override {
|
|
if (sound.IsValid()) {
|
|
sound.Unload();
|
|
}
|
|
}
|
|
|
|
bool Load(const std::string &path) {
|
|
if (sound.IsValid()) {
|
|
sound.Unload();
|
|
}
|
|
filePath = path;
|
|
sound.Load(filePath);
|
|
if (!sound.IsValid()) {
|
|
return false;
|
|
}
|
|
sound.SetVolume(volume);
|
|
sound.SetPitch(1.0f);
|
|
if (playOnStart) {
|
|
Play();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
void Play() {
|
|
if (!sound.IsValid()) {
|
|
return;
|
|
}
|
|
sound.Play();
|
|
}
|
|
|
|
void Stop() {
|
|
if (!sound.IsValid()) {
|
|
return;
|
|
}
|
|
sound.Stop();
|
|
}
|
|
|
|
void SetVolume(float newVolume) {
|
|
volume = std::clamp(newVolume, 0.0f, 1.0f);
|
|
if (sound.IsValid()) {
|
|
sound.SetVolume(volume);
|
|
}
|
|
}
|
|
|
|
private:
|
|
raylib::Sound sound;
|
|
};
|