Skip to content

Commit 6d1a2df

Browse files
examples/custom-sound-stream: Print time progress while playing
1 parent f44519b commit 6d1a2df

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

examples/custom-sound-stream.rs

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,15 @@ use sfml::{
55

66
// Melody by ryg - https://youtu.be/tCRPUv8V22o?t=176
77
struct BitMelody {
8-
buf: [i16; 2048],
8+
buf: [i16; BUF_SIZE],
99
t: i32,
10-
amp: i16,
10+
vol: i16,
1111
}
1212

13+
const FULLVOL_DURATION: i32 = 1_048_576;
14+
const INIT_VOL: i16 = 128;
15+
const BUF_SIZE: usize = 2048;
16+
1317
impl SoundStream for BitMelody {
1418
fn get_data(&mut self) -> (&mut [i16], bool) {
1519
for buf_sample in self.buf.iter_mut() {
@@ -20,13 +24,13 @@ impl SoundStream for BitMelody {
2024
let note = t * (i32::from(melody[index as usize]) & 15);
2125
let sample = ((note / 12) & 128)
2226
+ ((((((t >> 12) ^ ((t >> 12) - 2)) % 11 * t) / 4) | t >> 13) & 127);
23-
*buf_sample = sample as i16 * self.amp;
27+
*buf_sample = sample as i16 * self.vol;
2428
// Fade out after a while
25-
if t > 1_048_576 && t % 4096 == 0 {
26-
self.amp -= 1;
29+
if t > FULLVOL_DURATION && t % 4096 == 0 {
30+
self.vol -= 1;
2731
}
2832
}
29-
(&mut self.buf[..], self.amp > 0)
33+
(&mut self.buf[..], self.vol > 0)
3034
}
3135
fn seek(&mut self, offset: Time) {
3236
// Not exactly correct, but meh.
@@ -43,18 +47,25 @@ impl SoundStream for BitMelody {
4347
impl BitMelody {
4448
fn new() -> Self {
4549
BitMelody {
46-
buf: [0; 2048],
50+
buf: [0; BUF_SIZE],
4751
t: 0,
48-
amp: 128,
52+
vol: INIT_VOL,
4953
}
5054
}
55+
fn total_duration_samples(&self) -> usize {
56+
(FULLVOL_DURATION + INIT_VOL as i32 * 4096) as usize
57+
}
5158
}
5259

5360
fn main() {
5461
let mut stream = BitMelody::new();
62+
let total_dur = stream.total_duration_samples() as f32 / stream.sample_rate() as f32;
5563
let mut player = SoundStreamPlayer::new(&mut stream);
5664
player.play();
5765
while player.status() == SoundStatus::PLAYING {
66+
let current = player.playing_offset().as_seconds();
67+
eprint!("Playing custom sound stream: {current:06.03}/{total_dur:06.03}\r");
5868
std::thread::sleep(std::time::Duration::from_millis(100));
5969
}
70+
eprintln!();
6071
}

0 commit comments

Comments
 (0)