From 625126df686a782a54aaf79dbeced59911b3b953 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Sat, 13 May 2023 17:19:06 +1200 Subject: [PATCH] Fix i2s media player volume control (#4813) --- .../media_player/i2s_audio_media_player.cpp | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/esphome/components/i2s_audio/media_player/i2s_audio_media_player.cpp b/esphome/components/i2s_audio/media_player/i2s_audio_media_player.cpp index 2e9ded601d..4de1136987 100644 --- a/esphome/components/i2s_audio/media_player/i2s_audio_media_player.cpp +++ b/esphome/components/i2s_audio/media_player/i2s_audio_media_player.cpp @@ -22,14 +22,14 @@ void I2SAudioMediaPlayer::control(const media_player::MediaPlayerCall &call) { this->start(); } } - if (this->i2s_state_ != I2S_STATE_RUNNING) { - return; - } if (call.get_volume().has_value()) { this->volume = call.get_volume().value(); this->set_volume_(volume); this->unmute_(); } + if (this->i2s_state_ != I2S_STATE_RUNNING) { + return; + } if (call.get_command().has_value()) { switch (call.get_command().value()) { case media_player::MEDIA_PLAYER_COMMAND_PLAY: @@ -97,7 +97,8 @@ void I2SAudioMediaPlayer::unmute_() { this->muted_ = false; } void I2SAudioMediaPlayer::set_volume_(float volume, bool publish) { - this->audio_->setVolume(remap(volume, 0.0f, 1.0f, 0, 21)); + if (this->audio_ != nullptr) + this->audio_->setVolume(remap(volume, 0.0f, 1.0f, 0, 21)); if (publish) this->volume = volume; } @@ -157,13 +158,23 @@ void I2SAudioMediaPlayer::start_() { #endif this->i2s_state_ = I2S_STATE_RUNNING; this->high_freq_.start(); + this->audio_->setVolume(remap(this->volume, 0.0f, 1.0f, 0, 21)); if (this->current_url_.has_value()) { this->audio_->connecttohost(this->current_url_.value().c_str()); this->state = media_player::MEDIA_PLAYER_STATE_PLAYING; this->publish_state(); } } -void I2SAudioMediaPlayer::stop() { this->i2s_state_ = I2S_STATE_STOPPING; } +void I2SAudioMediaPlayer::stop() { + if (this->i2s_state_ == I2S_STATE_STOPPED) { + return; + } + if (this->i2s_state_ == I2S_STATE_STARTING) { + this->i2s_state_ = I2S_STATE_STOPPED; + return; + } + this->i2s_state_ = I2S_STATE_STOPPING; +} void I2SAudioMediaPlayer::stop_() { if (this->audio_->isRunning()) { this->audio_->stopSong();