ferravex_render/audio/
score.rs1use super::*;
2pub struct AdaptiveScore {
5 sounds: [Sound; 2],
6 voices: [Option<VoiceHandle>; 2],
7 clock: MusicConductor,
8 bpm: u16,
9}
10impl AdaptiveScore {
11 pub fn new(bpm: u16, seed: u32) -> Option<Self> {
12 Some(Self {
13 sounds: music_stems(SAMPLE_RATE, bpm, seed)?,
14 voices: [None; 2],
15 clock: MusicConductor::new(bpm)?,
16 bpm,
17 })
18 }
19 pub fn update(&mut self, dt: f32, intensity: f32) -> bool {
20 if !dt.is_finite()
21 || !(0. ..=0.25).contains(&dt)
22 || !intensity.is_finite()
23 || !(0. ..=1.).contains(&intensity)
24 {
25 return false;
26 }
27 if !self.voices.iter().all(|v| v.is_some_and(playing)) {
28 for v in &mut self.voices {
29 if let Some(h) = v.take() {
30 stop(h, 0);
31 }
32 }
33 self.clock = MusicConductor::new(self.bpm).unwrap();
34 for (sound, voice) in self.sounds.iter().zip(&mut self.voices) {
35 *voice = play_sound(
36 sound,
37 VoiceParams {
38 bus: Bus::Music,
39 gain: 0.,
40 looping: true,
41 priority: 1,
42 ..Default::default()
43 },
44 );
45 }
46 }
47 let frame = self.clock.update(dt, intensity).unwrap();
48 for (voice, gain) in self.voices.iter().zip(frame.gains) {
49 if let Some(h) = voice {
50 set_params(
51 *h,
52 VoiceParams {
53 bus: Bus::Music,
54 gain,
55 looping: true,
56 priority: 1,
57 ramp_frames: 1024,
58 ..Default::default()
59 },
60 );
61 }
62 }
63 true
64 }
65}
66impl Drop for AdaptiveScore {
67 fn drop(&mut self) {
68 for h in self.voices.iter().flatten() {
69 stop(*h, 128);
70 }
71 }
72}