mirror of
https://github.com/bevyengine/bevy
synced 2024-11-15 09:27:41 +00:00
ed151e756c
# Objective What's that? Another PR for the grand migration to required components? This time, audio! ## Solution Deprecate `AudioSourceBundle`, `AudioBundle`, and `PitchBundle`, as per the [chosen proposal](https://hackmd.io/@bevy/required_components/%2Fzxgp-zMMRUCdT7LY1ZDQwQ). However, we cannot call the component `AudioSource`, because that's what the stored asset is called. I deliberated on a few names, like `AudioHandle`, or even just `Audio`, but landed on `AudioPlayer`, since it's probably the most accurate and "nice" name for this. Open to alternatives though. --- ## Migration Guide Replace all insertions of `AudioSoucreBundle`, `AudioBundle`, and `PitchBundle` with the `AudioPlayer` component. The other components required by it will now be inserted automatically. In cases where the generics cannot be inferred, you may need to specify them explicitly. For example: ```rust commands.spawn(AudioPlayer::<AudioSource>(asset_server.load("sounds/sick_beats.ogg"))); ```
51 lines
1.4 KiB
Rust
51 lines
1.4 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::<AudioSource>(asset_server.load("sounds/Windless Slopes.ogg")),
|
|
MyMusic,
|
|
));
|
|
}
|
|
|
|
#[derive(Component)]
|
|
struct MyMusic;
|
|
|
|
fn update_speed(music_controller: Query<&AudioSink, With<MyMusic>>, time: Res<Time>) {
|
|
if let Ok(sink) = music_controller.get_single() {
|
|
sink.set_speed((ops::sin(time.elapsed_seconds() / 5.0) + 1.0).max(0.1));
|
|
}
|
|
}
|
|
|
|
fn pause(
|
|
keyboard_input: Res<ButtonInput<KeyCode>>,
|
|
music_controller: Query<&AudioSink, With<MyMusic>>,
|
|
) {
|
|
if keyboard_input.just_pressed(KeyCode::Space) {
|
|
if let Ok(sink) = music_controller.get_single() {
|
|
sink.toggle();
|
|
}
|
|
}
|
|
}
|
|
|
|
fn volume(
|
|
keyboard_input: Res<ButtonInput<KeyCode>>,
|
|
music_controller: Query<&AudioSink, With<MyMusic>>,
|
|
) {
|
|
if let Ok(sink) = music_controller.get_single() {
|
|
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);
|
|
}
|
|
}
|
|
}
|