-
Notifications
You must be signed in to change notification settings - Fork 243
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #668 from RustAudio/callback_on_source_end_example
adds example for emptycallback closing #651
- Loading branch information
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
use std::error::Error; | ||
use std::io::BufReader; | ||
use std::sync::atomic::{AtomicU32, Ordering}; | ||
use std::sync::Arc; | ||
|
||
fn main() -> Result<(), Box<dyn Error>> { | ||
let stream_handle = rodio::OutputStreamBuilder::open_default_stream()?; | ||
let sink = rodio::Sink::connect_new(&stream_handle.mixer()); | ||
|
||
let file = std::fs::File::open("assets/music.wav")?; | ||
sink.append(rodio::Decoder::new(BufReader::new(file))?); | ||
|
||
// lets increment a number after `music.wav` has played. We are going to use atomics | ||
// however you could also use a `Mutex` or send a message through a `std::sync::mpsc`. | ||
let playlist_pos = Arc::new(AtomicU32::new(0)); | ||
|
||
// The closure needs to own everything it uses. We move a clone of | ||
// playlist_pos into the closure. That way we can still access playlist_pos | ||
// after appending the EmptyCallback. | ||
let playlist_pos_clone = playlist_pos.clone(); | ||
sink.append(rodio::source::EmptyCallback::<f32>::new(Box::new( | ||
move || { | ||
println!("empty callback is now running"); | ||
playlist_pos_clone.fetch_add(1, Ordering::Relaxed); | ||
}, | ||
))); | ||
|
||
assert_eq!(playlist_pos.load(Ordering::Relaxed), 0); | ||
println!( | ||
"playlist position is: {}", | ||
playlist_pos.load(Ordering::Relaxed) | ||
); | ||
sink.sleep_until_end(); | ||
assert_eq!(playlist_pos.load(Ordering::Relaxed), 1); | ||
println!( | ||
"playlist position is: {}", | ||
playlist_pos.load(Ordering::Relaxed) | ||
); | ||
|
||
Ok(()) | ||
} |