Skip to content

Commit

Permalink
Add AudioFileHandle::toggle convenience method (#14)
Browse files Browse the repository at this point in the history
Closes #4

## Description

Adds a `AudioFileHandle::toggle` method for convenience.
  • Loading branch information
SolarLiner authored May 8, 2024
2 parents ad090ad + 359093a commit 1932421
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/sources/audio_file/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::backend::AudioBackend;
use crate::prelude::{AudioFileError, AudioFileSettings, AudioSource};
use crate::sources::audio_file;
use bevy::asset::Asset;
use bevy::prelude::TypePath;
use bevy::prelude::*;
use bevy::utils::error;
use kira::manager::error::PlaySoundError;
use kira::manager::AudioManager;
Expand Down Expand Up @@ -150,6 +150,26 @@ impl AudioFileHandle {
defer_call!(fn seek_by(&mut self, amount: f64) -> Result<(), CommandError>);
}

impl AudioFileHandle {
/// Convenience method to toggling the playback state of an audio file.
///
/// This is a simple wrapper around [`Self::pause`] and [`Self::resume`], which are called
/// depending on the current playback state.
///
/// Note that Kira has a special "stopped" state, which means the file has completely
/// finished playing, and cannot be resumed (an error will be logged if that's the case).
pub fn toggle(&mut self, tween: Tween) -> Result<(), CommandError> {
match self.playback_state() {
PlaybackState::Playing => self.pause(tween),
PlaybackState::Pausing | PlaybackState::Paused => self.resume(tween),
PlaybackState::Stopping | PlaybackState::Stopped => {
error!("Audio file has stopped and cannot be resumed again");
Ok(())
}
}
}
}

/// Enum of the possible sound handles that [`kira`] returns
enum RawAudioHandleImpl {
Static(StaticSoundHandle),
Expand Down

0 comments on commit 1932421

Please sign in to comment.