I'm trying to play some audio on my Pi, but I have reached a dead end with the borrowed value does not live long enough
, which does not make sense to me, because I create the variables in main
and afterwards enter an endless loop. Shouldn't welcome
& goodbye
live main
throughout the program execution?
Full error:
error[E0597]: `welcome` does not live long enough
--> src/main.rs:37:65
|
37 | let source = rodio::Decoder::new(BufReader::new(&welcome)).unwrap();
| ---------------^^^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `welcome` is borrowed for `'static`
...
54 | }
| - `welcome` dropped here while still borrowed
Line 54 is the closing bracket of 'main'.
What would be the Rust
way for such a thing? The program basically checks if it should change state and play some audio files if it does change.
fn main() {
// Audio setup
let (_stream, stream_handle) = rodio::OutputStream::try_default().unwrap();
let welcome = File::open("audio/welcome.mp3").unwrap();
let goodbye = File::open("audio/bye.mp3").unwrap();
loop {
sonar_state.state_tick();
let state = sonar_state.get_state();
match state {
StatusState::OnTrigger => {
// TODO make this a function where we pass in the file
let source = rodio::Decoder::new(BufReader::new(&welcome)).unwrap();
stream_handle.play_raw(source.convert_samples());
thread::sleep(Duration::from_millis(1000));
}
StatusState::OnTriggerEnd => {
// Nothing
}
StatusState::OffTrigger => {
let source = rodio::Decoder::new(BufReader::new(&goodbye)).unwrap();
stream_handle.play_raw(source.convert_samples());
thread::sleep(Duration::from_millis(1000));
}
StatusState::OffTriggerEnd => {
// Nothing
}
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…