我已经使用Rodio Crate通过文档来播放本地文件中的音频,但是无法弄清楚如何使用url播放音频。
答案 0 :(得分:1)
这是一个使用阻塞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
我相信使用异步reqwest也可以更轻松地完成此操作,但我仍在自己进行尝试。