Playing sounds
Play music and sound effects with AudioPlayer and PlaybackSettings, then pause, seek, fade and change the speed of a playing sound through its AudioSink.
On this page
A sound plays when an entity has an AudioPlayer. This page covers the settings a sound starts with, how to control it while it plays, and the common patterns: music that loops, effects that clean up after themselves and fades between tracks.
AudioPlayer and PlaybackSettings#
AudioPlayer::new(handle) takes a Handle<AudioSource> from the asset server. The sound starts as soon as the asset has loaded. Add PlaybackSettings to choose how; without it, the sound plays once.
PlaybackSettings | What it does |
|---|---|
PlaybackSettings::ONCE | Plays once and leaves the entity. |
PlaybackSettings::LOOP | Repeats forever. |
PlaybackSettings::DESPAWN | Plays once, then despawns the entity and its children. The usual choice for effects. |
PlaybackSettings::REMOVE | Plays once, then removes the audio components but keeps the entity. |
Each preset can be adjusted with builder methods:
| Method or field | What it sets |
|---|---|
with_volume(Volume) | The starting volume. |
with_speed(f32) | Playback speed, which also changes the pitch. 1.0 is normal. |
paused(), muted() | Start paused or muted. |
with_start_position(Duration) | Where to start in the sound. |
with_duration(Duration) | Stop after this long. |
with_spatial(true) | Place the sound in the world; see Spatial audio. |
PlaybackSettings only applies when a sound starts. Changing it later does nothing; use the sink instead.
Sound effects#
Load the effect once, keep the handle in a resource, and spawn a short-lived player each time it should play:
use neo::prelude::*;
#[derive(Resource, Deref)]
struct Bounce(Handle<AudioSource>);
impl FromWorld for Bounce {
fn from_world(world: &mut World) -> Self {
Bounce(world.resource::<AssetServer>().load("sounds/bounce.ogg"))
}
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_resource::<Bounce>()
.add_systems(Update, play_bounce)
.run();
}
fn play_bounce(keys: Res<ButtonInput<KeyCode>>, bounce: Res<Bounce>, mut commands: Commands) {
if keys.just_pressed(KeyCode::Space) {
commands.spawn((AudioPlayer::new(bounce.clone()), PlaybackSettings::DESPAWN));
}
}Controlling a playing sound#
Once a sound starts, the engine inserts an AudioSink on its entity (a SpatialAudioSink for spatial sounds). Query for it:
#[derive(Component)]
struct Music;
fn music_controls(keys: Res<ButtonInput<KeyCode>>, mut music: Query<&mut AudioSink, With<Music>>) {
let Ok(mut sink) = music.single_mut() else { return };
if keys.just_pressed(KeyCode::Space) {
sink.toggle_playback();
}
if keys.just_pressed(KeyCode::KeyM) {
sink.toggle_mute();
}
if keys.just_pressed(KeyCode::Equal) {
let v = sink.volume();
sink.set_volume(v.increase_by_percentage(10.0));
}
}| Method | What it does |
|---|---|
play(), pause(), toggle_playback(), is_paused() | Pause and resume. |
stop() | Stops for good. A stopped sink can't be restarted: spawn a new player. |
volume(), set_volume(Volume) | The sound's volume. |
mute(), unmute(), toggle_mute(), is_muted() | Mute without losing the volume. |
speed(), set_speed(f32) | Playback speed. |
position(), try_seek(Duration) | Where playback is, and jumping to a point. Not every format can seek. |
empty() | true once there's nothing left to play. |
Volume#
Volume is either Volume::Linear(x), where 1.0 is the sound's own level, or Volume::Decibels(db). Volume::SILENT is zero. Helpers work in either scale:
| Method | Returns |
|---|---|
to_linear(), to_decibels() | The value in one scale. |
increase_by_percentage(p), decrease_by_percentage(p) | A louder or quieter volume. |
fade_towards(target, factor) | A volume factor of the way (0 to 1) to target, for fades. |
Fading between tracks#
Start the new track silent and fade it up while the old one fades down:
use neo::audio::{PlaybackMode, Volume};
#[derive(Component)]
struct FadeIn { seconds: f32, elapsed: f32 }
fn start_track(mut commands: Commands, assets: Res<AssetServer>) {
commands.spawn((
AudioPlayer::new(assets.load("music/battle.ogg")),
PlaybackSettings { mode: PlaybackMode::Loop, volume: Volume::SILENT, ..default() },
FadeIn { seconds: 2.0, elapsed: 0.0 },
));
}
fn fade_in(mut commands: Commands, time: Res<Time>, mut q: Query<(Entity, &mut AudioSink, &mut FadeIn)>) {
for (entity, mut sink, mut fade) in &mut q {
fade.elapsed += time.delta_secs();
let t = (fade.elapsed / fade.seconds).min(1.0);
sink.set_volume(Volume::SILENT.fade_towards(Volume::Linear(1.0), t));
if t >= 1.0 {
commands.entity(entity).remove::<FadeIn>();
}
}
}The soundtrack example switches tracks by game state this way.
Sounds made in code#
A sound doesn't have to come from a file:
Pitch::new(frequency, duration)is a sine tone. Add it toAssets<Pitch>and play it withAudioPlayer(handle).- Any type that implements
Decodable(an iterator of samples with a channel count and sample rate) can be registered withapp.add_audio_source::<T>()and played like a file. NEO's audio kit registers its mixer this way.
Examples: cargo run --example audio, audio_control, play_sound_effect, soundtrack, pitch and decodable.