Skip to content

Commit

Permalink
Add a way to toggle AudioSink (bevyengine#6321)
Browse files Browse the repository at this point in the history
# 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.
  • Loading branch information
lovelymono authored and ItsDoot committed Feb 1, 2023
1 parent 0ce70ad commit ba9bb80
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
13 changes: 12 additions & 1 deletion crates/bevy_audio/src/audio_output.rs
Expand Up @@ -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()
}
Expand Down
6 changes: 1 addition & 5 deletions examples/audio/audio_control.rs
Expand Up @@ -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();
}
}
}
Expand Down

0 comments on commit ba9bb80

Please sign in to comment.