From 0f60d578fbd07091b3bb59f7ce1c515c4992b4a0 Mon Sep 17 00:00:00 2001 From: zhenyan121 <3367366583@qq.com> Date: Mon, 6 Jul 2026 17:28:36 +0800 Subject: [PATCH] fix(audio-source): improve state, volume, and const correctness --- include/Cubed/audio/audio_source.hpp | 2 +- src/audio/audio_source.cpp | 14 ++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/include/Cubed/audio/audio_source.hpp b/include/Cubed/audio/audio_source.hpp index fd71720..08a1979 100644 --- a/include/Cubed/audio/audio_source.hpp +++ b/include/Cubed/audio/audio_source.hpp @@ -20,7 +20,7 @@ public: float duration() const; float current_time() const; float volume() const; - AudioState state(); + AudioState state() const; private: ALuint m_source = 0; diff --git a/src/audio/audio_source.cpp b/src/audio/audio_source.cpp index 4c4f5e9..3c10cb7 100644 --- a/src/audio/audio_source.cpp +++ b/src/audio/audio_source.cpp @@ -1,7 +1,6 @@ #include "Cubed/audio/audio_source.hpp" -#include "Cubed/tools/log.hpp" - +#include #include namespace Cubed { @@ -14,7 +13,7 @@ AudioSource::~AudioSource() { } void AudioSource::set_buffer_2d(const AudioBuffer& buffer) { - if (state() == AudioState::PLAYING) { + if (state() != AudioState::STOPPED && state() != AudioState::INITIAL) { stop(); } m_duration = buffer.duration(); @@ -32,10 +31,7 @@ void AudioSource::set_loop(bool on) { } void AudioSource::set_volume(float volume) { - if (volume > 1.0f) { - Logger::error("Volume {} is too large", volume); - return; - } + volume = std::clamp(volume, 0.0f, 1.0f); m_volume = volume; alSourcef(m_source, AL_GAIN, volume); } @@ -53,7 +49,7 @@ float AudioSource::current_time() const { } float AudioSource::volume() const { return m_volume; } -AudioState AudioSource::state() { +AudioState AudioSource::state() const { ALint state; alGetSourcei(m_source, AL_SOURCE_STATE, &state); switch (state) { @@ -65,6 +61,8 @@ AudioState AudioSource::state() { return AudioState::STOPPED; case AL_PAUSED: return AudioState::PAUSED; + default: + throw std::runtime_error("Invalid OpenAL source state"); } throw std::runtime_error("Invaild state"); }