audiorustrodio

Playing audio from url in Rust


I have used rodio crate for playing audio from local file, by going through docs, but not able to figure out how to play audio using url.


Solution

  • Here is a simple example using blocking reqwest. This downloads the entire audio file into memory before it starts playing.

    use std::io::{Write, Read, Cursor};
    use rodio::Source;
    
    fn main() {
        // Remember to add the "blocking" feature in the Cargo.toml for reqwest
        let resp = reqwest::blocking::get("http://websrvr90va.audiovideoweb.com/va90web25003/companions/Foundations%20of%20Rock/13.01.mp3")
            .unwrap();
        let mut cursor = Cursor::new(resp.bytes().unwrap()); // Adds Read and Seek to the bytes via Cursor
        let source = rodio::Decoder::new(cursor).unwrap(); // Decoder requires it's source to impl both Read and Seek
        let device = rodio::default_output_device().unwrap();
        rodio::play_raw(&device, source.convert_samples()); // Plays on a different thread
        loop {} // Don't exit immediately, so we can hear the audio
    }
    

    If you want to implement actual streaming, where parts of the audio file is downloaded then played, and more gets fetched later as it is needed, it gets quite a bit more complicated. See this entry about partial downloads in the Rust Cookbook: https://rust-lang-nursery.github.io/rust-cookbook/web/clients/download.html#make-a-partial-download-with-http-range-headers

    I believe it can also be done easier with async reqwest, but I am still experimenting with that myself.