mirror of
https://github.com/bevyengine/bevy
synced 2024-12-22 11:03:06 +00:00
013e11a14f
# Objective `AudioPlayer::<AudioSource>(assets.load("audio.mp3"))` is awkward and complicated to type because the `AudioSource` generic type cannot be elided. This is especially annoying because `AudioSource` is used in the majority of cases. Most users don't need to think about it. ## Solution Add an `AudioPlayer::new()` function that is hard-coded to `AudioSource`, allowing `AudioPlayer::new(assets.load("audio.mp3"))`. Prefer using that in the relevant places.
39 lines
1.2 KiB
Rust
39 lines
1.2 KiB
Rust
//! This example illustrates how to load and play an audio file, and control how it's played.
|
|
|
|
use bevy::{math::ops, prelude::*};
|
|
|
|
fn main() {
|
|
App::new()
|
|
.add_plugins(DefaultPlugins)
|
|
.add_systems(Startup, setup)
|
|
.add_systems(Update, (update_speed, pause, volume))
|
|
.run();
|
|
}
|
|
|
|
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
|
|
commands.spawn((
|
|
AudioPlayer::new(asset_server.load("sounds/Windless Slopes.ogg")),
|
|
MyMusic,
|
|
));
|
|
}
|
|
|
|
#[derive(Component)]
|
|
struct MyMusic;
|
|
|
|
fn update_speed(sink: Single<&AudioSink, With<MyMusic>>, time: Res<Time>) {
|
|
sink.set_speed((ops::sin(time.elapsed_secs() / 5.0) + 1.0).max(0.1));
|
|
}
|
|
|
|
fn pause(keyboard_input: Res<ButtonInput<KeyCode>>, sink: Single<&AudioSink, With<MyMusic>>) {
|
|
if keyboard_input.just_pressed(KeyCode::Space) {
|
|
sink.toggle();
|
|
}
|
|
}
|
|
|
|
fn volume(keyboard_input: Res<ButtonInput<KeyCode>>, sink: Single<&AudioSink, With<MyMusic>>) {
|
|
if keyboard_input.just_pressed(KeyCode::Equal) {
|
|
sink.set_volume(sink.volume() + 0.1);
|
|
} else if keyboard_input.just_pressed(KeyCode::Minus) {
|
|
sink.set_volume(sink.volume() - 0.1);
|
|
}
|
|
}
|