start_timer/sound/
mod.rs

1mod track;
2
3use std::time::Duration;
4
5use anyhow::{Context, Result};
6use rodio::{OutputStream, OutputStreamHandle, Source};
7use track::{InMemoryTrackDecoder, Track};
8
9pub struct Sound {
10    source: InMemoryTrackDecoder,
11    stream_handle: OutputStreamHandle,
12    duration: Duration,
13    /// If this is dropped playback will end & attached
14    /// `OutputStreamHandle`s will no longer work.
15    #[allow(dead_code)]
16    output_stream: OutputStream,
17}
18
19impl Sound {
20    pub fn new() -> Result<Self> {
21        let (output_stream, stream_handle) =
22            OutputStream::try_default().context("Failed to retrieve output stream")?;
23        let track = Track::Calm.load().context("Failed to decode music file")?;
24
25        Ok(Sound {
26            source: track.decoder,
27            duration: track.duration,
28            output_stream,
29            stream_handle,
30        })
31    }
32
33    pub fn play(self) -> Result<()> {
34        self.stream_handle
35            .play_raw(self.source.convert_samples())
36            .context("Failed to play raw audio")?;
37        std::thread::sleep(self.duration);
38
39        Ok(())
40    }
41}