From 599ca782e3159b95db3808af22f9abac9bbbe005 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lena=20Miliz=C3=A9?= Date: Mon, 31 Oct 2022 15:57:51 +0000 Subject: [PATCH] Add a way to toggle `AudioSink` (#6321) # Objective Currently toggling an `AudioSink` (for example from a game menu) requires writing ```rs if sink.is_paused() { sink.play(); } else { sink.pause(); } ``` It would be nicer if we could reduce this down to a single line ```rs sink.toggle(); ``` ## Solution Add an `AudioSink::toggle` method which does exactly that. --- ## Changelog - Added `AudioSink::toggle` which can be used to toggle state of a sink. --- crates/bevy_audio/src/audio_output.rs | 13 ++++++++++++- examples/audio/audio_control.rs | 6 +----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/bevy_audio/src/audio_output.rs b/crates/bevy_audio/src/audio_output.rs index b4f942c7c84c9..f42db09df654c 100644 --- a/crates/bevy_audio/src/audio_output.rs +++ b/crates/bevy_audio/src/audio_output.rs @@ -178,9 +178,20 @@ impl AudioSink { self.sink.as_ref().unwrap().pause(); } + /// Toggles the playback of this sink. + /// + /// Will pause if playing, and will be resumed if paused. + pub fn toggle(&self) { + if self.is_paused() { + self.play(); + } else { + self.pause(); + } + } + /// Is this sink paused? /// - /// Sinks can be paused and resumed using [`pause`](Self::pause) and [`play`](Self::play). + /// Sinks can be paused and resumed using [`pause`](Self::pause), [`play`](Self::play), and [`toggle`](Self::toggle). pub fn is_paused(&self) -> bool { self.sink.as_ref().unwrap().is_paused() } diff --git a/examples/audio/audio_control.rs b/examples/audio/audio_control.rs index d5344e68ead8b..85598082276a7 100644 --- a/examples/audio/audio_control.rs +++ b/examples/audio/audio_control.rs @@ -43,11 +43,7 @@ fn pause( ) { if keyboard_input.just_pressed(KeyCode::Space) { if let Some(sink) = audio_sinks.get(&music_controller.0) { - if sink.is_paused() { - sink.play(); - } else { - sink.pause(); - } + sink.toggle(); } } }