我正在通过 Rust 直接下载 MP3 音频流。由于这个流是不确定的,我希望能够提前取消它以保存我到目前为止下载的内容。目前,我通过按 CTRL + C 来停止程序。这会生成一个 stream.mp3 文件,然后我可以播放和收听,虽然这可行,但并不理想。
给定以下代码,我如何以编程方式io::copy()
提前停止并让它保存文件而不杀死整个程序?
extern crate reqwest;
use std::io;
use std::fs::File;
// Note that this is a direct link to the stream, not a webpage with HTML and a stream
const STREAM_URL: &str = "http://path.to/stream";
fn main() {
let mut response = reqwest::get(STREAM_URL)
.expect("Failed to request mp3 stream");
let mut output = File::create("stream.mp3")
.expect("Failed to create file!");
io::copy(&mut response, &mut output)
.expect("Failed to copy mp3 stream to file");
}