Skip to content

Commit

Permalink
Audio control at start of playback (bevyengine#4110)
Browse files Browse the repository at this point in the history
# Objective

- While playing with volume, I noticed that when setting the volume just after playback start, I still get a few milliseconds at normal volume

## Solution

- Replace `play_in_loop` with `play_with_settings` that allows from more controls
- Adds a `PlaybackSettings` to specify the settings from start. Can be used: `PlaybackSettings::LOOP.with_volume(0.75)`
  • Loading branch information
mockersf committed Apr 8, 2022
1 parent c12ee81 commit e8cd2fc
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 10 deletions.
79 changes: 71 additions & 8 deletions crates/bevy_audio/src/audio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,21 +78,39 @@ where
pub fn play(&self, audio_source: Handle<Source>) -> Handle<AudioSink> {
let id = HandleId::random::<AudioSink>();
let config = AudioToPlay {
repeat: false,
settings: PlaybackSettings::ONCE,
sink_handle: id,
source_handle: audio_source,
};
self.queue.write().push_back(config);
Handle::<AudioSink>::weak(id)
}

/// Play audio from a [`Handle`] to the audio source in a loop
/// Play audio from a [`Handle`] to the audio source with [`PlaybackSettings`] that
/// allows looping or changing volume from the start.
///
/// See [`Self::play`] on how to control playback.
pub fn play_in_loop(&self, audio_source: Handle<Source>) -> Handle<AudioSink> {
/// ```
/// # use bevy_ecs::system::Res;
/// # use bevy_asset::AssetServer;
/// # use bevy_audio::Audio;
/// # use bevy_audio::PlaybackSettings;
/// fn play_audio_system(asset_server: Res<AssetServer>, audio: Res<Audio>) {
/// audio.play_with_settings(
/// asset_server.load("my_sound.ogg"),
/// PlaybackSettings::LOOP.with_volume(0.75),
/// );
/// }
/// ```
///
/// See [`Self::play`] on how to control playback once it's started.
pub fn play_with_settings(
&self,
audio_source: Handle<Source>,
settings: PlaybackSettings,
) -> Handle<AudioSink> {
let id = HandleId::random::<AudioSink>();
let config = AudioToPlay {
repeat: true,
settings,
sink_handle: id,
source_handle: audio_source,
};
Expand All @@ -101,14 +119,59 @@ where
}
}

#[derive(Clone, PartialEq, Eq)]
/// Settings to control playback from the start.
#[derive(Clone, Debug)]
pub struct PlaybackSettings {
/// Play in repeat
pub repeat: bool,
/// Volume to play at.
pub volume: f32,
/// Speed to play at.
pub speed: f32,
}

impl Default for PlaybackSettings {
fn default() -> Self {
Self::ONCE
}
}

impl PlaybackSettings {
/// Will play the associate audio source once.
pub const ONCE: PlaybackSettings = PlaybackSettings {
repeat: false,
volume: 1.0,
speed: 1.0,
};

/// Will play the associate audio source in a loop.
pub const LOOP: PlaybackSettings = PlaybackSettings {
repeat: true,
volume: 1.0,
speed: 1.0,
};

/// Helper to set the volume from start of playback.
pub const fn with_volume(mut self, volume: f32) -> Self {
self.volume = volume;
self
}

/// Helper to set the speed from start of playback.
pub const fn with_speed(mut self, speed: f32) -> Self {
self.speed = speed;
self
}
}

#[derive(Clone)]
pub(crate) struct AudioToPlay<Source>
where
Source: Asset + Decodable,
{
pub(crate) sink_handle: HandleId,
pub(crate) source_handle: Handle<Source>,
pub(crate) repeat: bool,
pub(crate) settings: PlaybackSettings,
}

impl<Source> fmt::Debug for AudioToPlay<Source>
Expand All @@ -119,7 +182,7 @@ where
f.debug_struct("AudioToPlay")
.field("sink_handle", &self.sink_handle)
.field("source_handle", &self.source_handle)
.field("repeat", &self.repeat)
.field("settings", &self.settings)
.finish()
}
}
12 changes: 11 additions & 1 deletion crates/bevy_audio/src/audio_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,10 @@ where
while i < len {
let config = queue.pop_front().unwrap();
if let Some(audio_source) = audio_sources.get(&config.source_handle) {
if let Some(sink) = self.play_source(audio_source, config.repeat) {
if let Some(sink) = self.play_source(audio_source, config.settings.repeat) {
sink.set_speed(config.settings.speed);
sink.set_volume(config.settings.volume);

// don't keep the strong handle. there is no way to return it to the user here as it is async
let _ = sinks.set(config.sink_handle, AudioSink { sink: Some(sink) });
}
Expand Down Expand Up @@ -186,4 +189,11 @@ impl AudioSink {
pub fn is_paused(&self) -> bool {
self.sink.as_ref().unwrap().is_paused()
}

/// Stops the sink.
///
/// It won't be possible to restart it afterwards.
pub fn stop(&self) {
self.sink.as_ref().unwrap().stop();
}
}
2 changes: 1 addition & 1 deletion crates/bevy_audio/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ mod audio_source;
#[allow(missing_docs)]
pub mod prelude {
#[doc(hidden)]
pub use crate::{Audio, AudioOutput, AudioSource, Decodable};
pub use crate::{Audio, AudioOutput, AudioSource, Decodable, PlaybackSettings};
}

pub use audio::*;
Expand Down

0 comments on commit e8cd2fc

Please sign in to comment.