Skip to content

Commit 599ca78

Browse files
committed
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.
1 parent 13da481 commit 599ca78

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed

crates/bevy_audio/src/audio_output.rs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,9 +178,20 @@ impl AudioSink {
178178
self.sink.as_ref().unwrap().pause();
179179
}
180180

181+
/// Toggles the playback of this sink.
182+
///
183+
/// Will pause if playing, and will be resumed if paused.
184+
pub fn toggle(&self) {
185+
if self.is_paused() {
186+
self.play();
187+
} else {
188+
self.pause();
189+
}
190+
}
191+
181192
/// Is this sink paused?
182193
///
183-
/// Sinks can be paused and resumed using [`pause`](Self::pause) and [`play`](Self::play).
194+
/// Sinks can be paused and resumed using [`pause`](Self::pause), [`play`](Self::play), and [`toggle`](Self::toggle).
184195
pub fn is_paused(&self) -> bool {
185196
self.sink.as_ref().unwrap().is_paused()
186197
}

examples/audio/audio_control.rs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,7 @@ fn pause(
4343
) {
4444
if keyboard_input.just_pressed(KeyCode::Space) {
4545
if let Some(sink) = audio_sinks.get(&music_controller.0) {
46-
if sink.is_paused() {
47-
sink.play();
48-
} else {
49-
sink.pause();
50-
}
46+
sink.toggle();
5147
}
5248
}
5349
}

0 commit comments

Comments
 (0)