RustAudio / rodio

Rust audio playback library
Apache License 2.0
1.78k stars 232 forks source link

Sink append too slow #526

Open zhangzqs opened 11 months ago

zhangzqs commented 11 months ago

I need realtime player, my code is like follow, sink "append" is more and more slow

pub struct RodioPlayer {
    stream: rodio::OutputStream,
    stream_handle: rodio::OutputStreamHandle,
    sink: rodio::Sink,
}

impl RodioPlayer {
    pub fn new() -> Self {
        let (stream, stream_handle) = rodio::OutputStream::try_default().unwrap();

        let sink = rodio::Sink::try_new(&stream_handle).unwrap();

        Self {
            sink,
            stream,
            stream_handle,
        }
    }

    fn tone(&mut self, freq: u32) {
        println!("tone {}", freq);
        self.sink.stop();
        let now = std::time::Instant::now();
        self.sink.append(SineWave::new(freq as f32));
        println!("append takes {:?}", now.elapsed());
    }

    fn off(&mut self) {
        self.sink.stop();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn test_tone() {
        let mut player = RodioPlayer::new();
        let src = "0 830\n790 0\n0 659\n3309 0\n1 440\n102 0\n104 391\n68 0\n1 440\n68 0\n1 391\n68 0\n1 329\n102 0\n104 391\n103 0\n104 440\n102 0\n104 391\n68 0\n1 440\n68 0\n1 391\n68 0\n1 329\n102 0\n104 391\n102 0\n104 440\n102 0\n104 391\n68 0\n1 440\n68 0\n1 391\n68 0\n1 329\n103 0\n104 391\n102 0\n104 440\n309 0\n311 391\n102 0\n104 440\n103 0\n104 391\n68 0\n1 440\n68 0\n1 391\n68 0\n1 329\n102 0\n104 391\n102 0\n105 440\n102 0\n105 391\n68 0\n1 440\n68 0\n1 391\n68 0\n1 329\n102 0\n104 391\n102 0\n104 440\n103 0\n104 391\n68 0\n1 440\n68 0\n1 391\n68 0\n1 329\n102 0\n104 391\n102 0\n104 440\n309 0\n311 391\n102 0\n104 880\n102 0\n105 880\n2688 0\n208 1046\n102 0\n104 1174\n1654 0\n208 1318\n111 0\n104 1318\n112 0\n104 1318\n112 0\n104 1318\n215 0\n208 1318";
        src.split("\n")
            .map(|x| {
                let mut x = x.split_whitespace();
                let d = x.next().unwrap().parse::<u64>().unwrap();
                let f = x.next().unwrap().parse::<u32>().unwrap();
                (d, f)
            })
            .for_each(|(d, f)| {
                std::thread::sleep(Duration::from_millis(d));
                player.tone(f);
            });
    }
}

image

est31 commented 11 months ago

That's strange. Are you using release mode?

zhangzqs commented 11 months ago

That's strange. Are you using release mode?

Both debug and release are equally slow

zhangzqs commented 11 months ago

image I found this function call in append is very slow

zhangzqs commented 10 months ago

I found the code in WSL2 is very slow, but in Windows is normal