在 Rust 中播放来自 url 的音频

Playing audio from url in Rust

我已经使用 rodio crate 通过文档播放本地文件中的音频,但无法弄清楚如何使用 url.

播放音频

这是一个使用阻塞 reqwest 的简单示例。这会在开始播放之前将整个音频文件下载到内存中。

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
}

如果您想实现实际的流式传输,下载部分音频文件然后播放,并在需要时获取更多内容,这会变得更加复杂。请参阅 Rust Cookbook 中有关部分下载的条目:https://rust-lang-nursery.github.io/rust-cookbook/web/clients/download.html#make-a-partial-download-with-http-range-headers

我相信使用 async reqwest 也可以更轻松地完成它,但我自己仍在试验。