1use bevy::prelude::*;
4use std::time::Duration;
5
6fn main() {
7 App::new()
8 .add_plugins(DefaultPlugins)
9 .add_message::<PlayPitch>()
10 .add_systems(Startup, setup)
11 .add_systems(Update, (play_pitch, keyboard_input_system))
12 .run();
13}
14
15#[derive(Message, Default)]
16struct PlayPitch;
17
18#[derive(Resource)]
19struct PitchFrequency(f32);
20
21fn setup(mut commands: Commands) {
22 commands.insert_resource(PitchFrequency(220.0));
23}
24
25fn play_pitch(
26 mut pitch_assets: ResMut<Assets<Pitch>>,
27 frequency: Res<PitchFrequency>,
28 mut play_pitch_reader: MessageReader<PlayPitch>,
29 mut commands: Commands,
30) {
31 for _ in play_pitch_reader.read() {
32 info!("playing pitch with frequency: {}", frequency.0);
33 commands.spawn((
34 AudioPlayer(pitch_assets.add(Pitch::new(frequency.0, Duration::new(1, 0)))),
35 PlaybackSettings::DESPAWN,
36 ));
37 info!("number of pitch assets: {}", pitch_assets.len());
38 }
39}
40
41fn keyboard_input_system(
42 keyboard_input: Res<ButtonInput<KeyCode>>,
43 mut frequency: ResMut<PitchFrequency>,
44 mut play_pitch_writer: MessageWriter<PlayPitch>,
45) {
46 if keyboard_input.just_pressed(KeyCode::ArrowUp) {
47 frequency.0 *= ops::powf(2.0f32, 1.0 / 12.0);
48 }
49 if keyboard_input.just_pressed(KeyCode::ArrowDown) {
50 frequency.0 /= ops::powf(2.0f32, 1.0 / 12.0);
51 }
52 if keyboard_input.just_pressed(KeyCode::Space) {
53 play_pitch_writer.write(PlayPitch);
54 }
55}