morse_lib/
sound.rs

1use std::time::Duration;
2
3use rodio::{source::SineWave, OutputStream, Sink, Source};
4
5/// ## Audio part for Morse Code (feature).
6#[derive(Debug, PartialEq, Clone)]
7pub struct Sound {
8    pub frequency: f32,
9    pub speed: f32,
10}
11
12impl Default for Sound {
13    fn default() -> Self {
14        Self {
15            frequency: 450.0,
16            speed: 1.0,
17        }
18    }
19}
20
21impl TSound for Sound {}
22
23pub trait TSound {
24    fn play(&self, freq: f32, duration: u8, speed: f32) {
25        // on linux require pkg-config libudev-dev libasound2-dev
26        // _stream must live as long as the sink
27        let (_stream, stream_handle) = OutputStream::try_default().unwrap();
28        let sink = Sink::try_new(&stream_handle).unwrap();
29
30        // Add a dummy source of the sake of the example.
31        let source = SineWave::new(freq)
32            .take_duration(Duration::from_secs_f32((duration as f32) / speed))
33            .amplify(0.20);
34        sink.append(source);
35
36        // The sound plays in a separate thread. This call will block the current thread until the sink
37        // has finished playing all its queued sounds.
38        sink.sleep_until_end();
39    }
40}