Sound.cpp
Sound.cpp
CPP1/* Copyright Statement:2 *3 * (C) 2021-2024 Cubios Inc. All rights reserved.4 */56#include "Sound.h"78namespace Cubios9{10 Sound::Sound(const std::string& name)11 {12 id = SND_getAssetId(name.c_str());13 }1415 Sound::~Sound() { }1617 void Sound::Play(uint8_t volume)18 {19 SND_play(id, volume);20 }2122 void Sound::Stop()23 {24 SND_stop();25 }2627 bool Sound::IsPlaying()28 {29 return SND_isPlaying();30 }313233 SoundCollection::SoundCollection(std::vector<std::string>& names):currentSound(nullptr),delay(0)34 {35 this->numSounds = names.size();36 this->external = false;3738 for(size_t i=0;i<this->numSounds;i++)39 {40 this->sounds.push_back(new Sound(names.at(i)));41 }42 }4344 SoundCollection::SoundCollection(std::vector<Cubios::Sound*>& sounds):currentSound(nullptr),delay(0)45 {46 this->numSounds = sounds.size();47 this->external = true;4849 for(size_t i=0;i<this->numSounds;i++)50 {51 this->sounds.push_back(sounds.at(i));52 }5354 }5556 SoundCollection::~SoundCollection()57 {58 if(!this->external)59 {60 for(size_t i=0;i<this->numSounds;i++)61 {62 Cubios::Sound* s = this->sounds.at(i);63 if(s!=nullptr)64 {65 if(s->IsPlaying()) s->Stop();66 delete s;67 }68 }69 }70 }7172 void SoundCollection::Stop()73 {74 if(this->currentSound!=nullptr)75 {76 this->currentSound->Stop();77 this->currentSound = nullptr;78 this->delay = 0;79 }80 }8182 bool SoundCollection::IsPlaying()83 {84 if(this->currentSound!=nullptr)85 {86 return this->currentSound->IsPlaying();87 }88 else return false;89 }9091 bool SoundCollection::PlayRandomSound(uint8_t volume, bool stopCurrent)92 {93 if(this->currentSound!=nullptr)94 {95 if(this->currentSound->IsPlaying())96 {97 if(stopCurrent)98 {99 this->currentSound->Stop();100 this->currentSound = nullptr;101 }102 else103 {104 return false;105 }106 }107 }108109 this->currentSound = this->sounds.at(Cubios::random(0, this->numSounds-1));110 this->currentSound->Play(volume);111 return true;112 }113114 bool SoundCollection::RepeatRandomSounds(uint8_t volume, int delayMin, int delayMax, int deltaTime)115 {116 if(this->currentSound!=nullptr)117 if(this->currentSound->IsPlaying()) return false;118119 if(this->delay<=0)120 {121 this->delay = Cubios::random(delayMin, delayMax);122 }123 else124 {125 this->delay-=deltaTime;126 return false;127 }128129 this->currentSound = this->sounds.at(Cubios::random(0, this->numSounds-1));130 this->currentSound->Play(volume);131 return true;132 }133134} // namespace Cubios135
Wrapped for easier reading. Turn wrap off to inspect exact line lengths.