From 2f971c96a17ccb8950c7ecd7233501e938dab2cd Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Tue, 8 Dec 2020 16:19:46 -0600 Subject: [PATCH] fix: move audio playback into another thread --- src/alert.rs | 26 ++++++++++++++++++-------- src/pomodoro.rs | 2 +- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/alert.rs b/src/alert.rs index ea740f6..918fab4 100644 --- a/src/alert.rs +++ b/src/alert.rs @@ -1,5 +1,4 @@ -use rodio::{Decoder, Source, OutputStream}; -use std::error::Error; +use rodio::{Decoder, OutputStream, Sink, Source}; use std::fs::File; use std::io::BufReader; use std::path::PathBuf; @@ -18,12 +17,23 @@ impl Alert { self.path = path; } - pub fn play(&self) -> Result<(), Box> { - let (_, handle) = OutputStream::try_default()?; - let file = File::open(&self.path)?; - let source = Decoder::new(BufReader::new(file))?; + pub fn play(&self) { + let file = File::open(&self.path).unwrap(); - handle.play_raw(source.convert_samples()).unwrap(); // use ?, blocked: https://github.com/RustAudio/rodio/pull/329 - Ok(()) + std::thread::spawn(move || { + let (_stream, handle) = OutputStream::try_default().unwrap(); + let source = Decoder::new(BufReader::new(file)).unwrap(); + let sink = Sink::try_new(&handle).unwrap(); + + sink.append(source); + + loop { + if sink.len() == 0 { + break; + } + } + + println!("Exited Playback Thread."); + }); } } diff --git a/src/pomodoro.rs b/src/pomodoro.rs index e108509..a2108e6 100644 --- a/src/pomodoro.rs +++ b/src/pomodoro.rs @@ -132,7 +132,7 @@ impl Pomodoro { }; if let Some(alert) = maybe_alert { - let _ = alert.play(); + alert.play() } let _ = self.notify();