Monad Engine da02fba2
> Undercity Codex_
Loading...
Searching...
No Matches
AudioComponent.cpp
Go to the documentation of this file.
1#include "scene/components/AudioComponent.h"
2
3#include "scene/GameObject.h"
4
5namespace mnd
6{
7void AudioComponent::LoadProperties(const nlohmann::json &json)
8{
9 if (json.contains("audio"))
10 {
11 auto &clipsObject = json["audio"];
12 for (auto &clip : clipsObject)
13 {
14 std::string name = clip.value("name", "noname");
15 std::string path = clip.value("path", "");
16 auto audio = Audio::Load(path);
17 if (audio)
18 {
19 float volume = clip.value("volume", 1.0f);
20 audio->SetVolume(volume);
21 RegisterAudio(name, audio);
22 }
23 }
24 }
25}
26
27void AudioComponent::Update(float deltaTime)
28{
29 auto pos = m_owner->GetWorldPosition();
30 for (auto &clip : m_clips)
31 {
32 if (clip.second->IsPlaying())
33 {
34 clip.second->SetPosition(pos);
35 }
36 }
37}
38
39void AudioComponent::RegisterAudio(const std::string &name, std::shared_ptr<Audio> &clip)
40{
41 m_clips[name] = clip;
42}
43
44void AudioComponent::Play(const std::string &name, bool loop)
45{
46 auto it = m_clips.find(name);
47 if (it != m_clips.end())
48 {
49 if (it->second)
50 {
51 it->second->Play(loop);
52 }
53 }
54}
55
56void AudioComponent::Stop(const std::string &name)
57{
58 auto it = m_clips.find(name);
59 if (it != m_clips.end())
60 {
61 if (it->second)
62 {
63 it->second->Stop();
64 }
65 }
66}
67
68bool AudioComponent::IsPlaying(const std::string &name)
69{
70 auto it = m_clips.find(name);
71 if (it != m_clips.end())
72 {
73 if (it->second)
74 {
75 return it->second->IsPlaying();
76 }
77 }
78
79 return false;
80}
81} // namespace mnd
82
void RegisterAudio(const std::string &name, std::shared_ptr< Audio > &clip)
Add a clip under name; later calls reference it by that key.
void LoadProperties(const nlohmann::json &json) override
Read clips and properties from a serialised scene JSON entry.
bool IsPlaying(const std::string &name)
True iff the named clip is currently playing.
void Play(const std::string &name, bool loop=false)
Start the named clip; loop true loops forever.
void Update(float deltaTime) override
Push the owner's world position to every registered clip.
void Stop(const std::string &name)
Stop the named clip if it is currently playing.
static std::shared_ptr< Audio > Load(const std::string &path)
Decode an audio file from disk and return a shared instance.
Definition Audio.cpp:74
GameObject * m_owner
Definition Component.h:57
vec3 GetWorldPosition() const
Extract the world-space position from GetWorldTransform().