Skip to content

Commit

Permalink
examples/custom-sound-stream: Print time progress while playing
Browse files Browse the repository at this point in the history
  • Loading branch information
crumblingstatue committed Jul 9, 2024
1 parent f44519b commit 6d1a2df
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions examples/custom-sound-stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ use sfml::{

// Melody by ryg - https://youtu.be/tCRPUv8V22o?t=176
struct BitMelody {
buf: [i16; 2048],
buf: [i16; BUF_SIZE],
t: i32,
amp: i16,
vol: i16,
}

const FULLVOL_DURATION: i32 = 1_048_576;
const INIT_VOL: i16 = 128;
const BUF_SIZE: usize = 2048;

impl SoundStream for BitMelody {
fn get_data(&mut self) -> (&mut [i16], bool) {
for buf_sample in self.buf.iter_mut() {
Expand All @@ -20,13 +24,13 @@ impl SoundStream for BitMelody {
let note = t * (i32::from(melody[index as usize]) & 15);
let sample = ((note / 12) & 128)
+ ((((((t >> 12) ^ ((t >> 12) - 2)) % 11 * t) / 4) | t >> 13) & 127);
*buf_sample = sample as i16 * self.amp;
*buf_sample = sample as i16 * self.vol;
// Fade out after a while
if t > 1_048_576 && t % 4096 == 0 {
self.amp -= 1;
if t > FULLVOL_DURATION && t % 4096 == 0 {
self.vol -= 1;
}
}
(&mut self.buf[..], self.amp > 0)
(&mut self.buf[..], self.vol > 0)
}
fn seek(&mut self, offset: Time) {
// Not exactly correct, but meh.
Expand All @@ -43,18 +47,25 @@ impl SoundStream for BitMelody {
impl BitMelody {
fn new() -> Self {
BitMelody {
buf: [0; 2048],
buf: [0; BUF_SIZE],
t: 0,
amp: 128,
vol: INIT_VOL,
}
}
fn total_duration_samples(&self) -> usize {
(FULLVOL_DURATION + INIT_VOL as i32 * 4096) as usize
}
}

fn main() {
let mut stream = BitMelody::new();
let total_dur = stream.total_duration_samples() as f32 / stream.sample_rate() as f32;
let mut player = SoundStreamPlayer::new(&mut stream);
player.play();
while player.status() == SoundStatus::PLAYING {
let current = player.playing_offset().as_seconds();
eprint!("Playing custom sound stream: {current:06.03}/{total_dur:06.03}\r");
std::thread::sleep(std::time::Duration::from_millis(100));
}
eprintln!();
}

0 comments on commit 6d1a2df

Please sign in to comment.