mirror of
https://github.com/bevyengine/bevy
synced 2024-12-29 22:43:14 +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"))); ```
55 lines
1.5 KiB
Rust
55 lines
1.5 KiB
Rust
//! This example illustrates how to play a single-frequency sound (aka a pitch)
|
|
|
|
use bevy::prelude::*;
|
|
use std::time::Duration;
|
|
|
|
fn main() {
|
|
App::new()
|
|
.add_plugins(DefaultPlugins)
|
|
.add_event::<PlayPitch>()
|
|
.add_systems(Startup, setup)
|
|
.add_systems(Update, (play_pitch, keyboard_input_system))
|
|
.run();
|
|
}
|
|
|
|
#[derive(Event, Default)]
|
|
struct PlayPitch;
|
|
|
|
#[derive(Resource)]
|
|
struct PitchFrequency(f32);
|
|
|
|
fn setup(mut commands: Commands) {
|
|
commands.insert_resource(PitchFrequency(220.0));
|
|
}
|
|
|
|
fn play_pitch(
|
|
mut pitch_assets: ResMut<Assets<Pitch>>,
|
|
frequency: Res<PitchFrequency>,
|
|
mut events: EventReader<PlayPitch>,
|
|
mut commands: Commands,
|
|
) {
|
|
for _ in events.read() {
|
|
info!("playing pitch with frequency: {}", frequency.0);
|
|
commands.spawn((
|
|
AudioPlayer(pitch_assets.add(Pitch::new(frequency.0, Duration::new(1, 0)))),
|
|
PlaybackSettings::DESPAWN,
|
|
));
|
|
info!("number of pitch assets: {}", pitch_assets.len());
|
|
}
|
|
}
|
|
|
|
fn keyboard_input_system(
|
|
keyboard_input: Res<ButtonInput<KeyCode>>,
|
|
mut frequency: ResMut<PitchFrequency>,
|
|
mut events: EventWriter<PlayPitch>,
|
|
) {
|
|
if keyboard_input.just_pressed(KeyCode::ArrowUp) {
|
|
frequency.0 *= ops::powf(2.0f32, 1.0 / 12.0);
|
|
}
|
|
if keyboard_input.just_pressed(KeyCode::ArrowDown) {
|
|
frequency.0 /= ops::powf(2.0f32, 1.0 / 12.0);
|
|
}
|
|
if keyboard_input.just_pressed(KeyCode::Space) {
|
|
events.send(PlayPitch);
|
|
}
|
|
}
|