本系列教程对应的代码已开源在 Github zeedle
在Cargo.toml添加:
[dependencies]
rodio = "0.21.1"
use std::{thread, time::Duration};
use rodio::Decoder;
fn main() {
// create an output stream
let stream_handle = rodio::OutputStreamBuilder::from_default_device()
.expect("no output device available")
.open_stream()
.expect("failed to open output stream");
// create a sink to play audio
let sink = rodio::Sink::connect_new(&stream_handle.mixer());
// open an audio file
let file = std::fs::File::open("audios/爱情转移.flac").expect("failed to open audio file");
// decode the audio file
let source = Decoder::try_from(file).expect("failed to decode audio file");
// append the audio source to the sink & auto play
sink.append(source);
// sleep for a while to let the audio play
thread::sleep(Duration::from_secs(20));
// pause the audio playback explicitly
sink.pause();
// sleep for a while
thread::sleep(Duration::from_secs(20));
// resume the audio playback explicitly
sink.play();
// keep the main thread alive while the audio is playing
thread::sleep(Duration::from_secs(20));
}
执行上述代码,会:
如果sink.append之后没有thread::sleep,程序会立刻结束,任何声音都不会被播放,这是因为,根据Rust变量的生命周期,stream_handle变量会在main函数右括号}
处立刻释放,由于stream_handle管理了计算机音频输出设备硬件资源,当它超出生命周期被释放时,与之关联的任何音频播放(也就是sink中存在的所有source)都会被强制停止,这是Rodio库为了保护硬件资源做出的一个设计,大大减小了硬件不可控事件的出现。
还有一些额外的事情需要注意:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。