prototty_native_audio/
audio_on_main_thread.rs

1use crate::common;
2use crate::Error;
3use prototty_audio::{AudioPlayer, AudioProperties};
4use rodio::source::Source;
5use rodio::{Decoder, Device, Sink};
6use std::io::Cursor;
7
8pub struct NativeAudioPlayer {
9    device: Device,
10}
11impl NativeAudioPlayer {
12    pub fn try_new_default_device() -> Result<Self, Error> {
13        let device = common::output_device().ok_or(Error::NoOutputDevice)?;
14        Ok(Self { device })
15    }
16
17    pub fn new_default_device() -> Self {
18        Self::try_new_default_device().unwrap()
19    }
20
21    pub fn play(&self, sound: &NativeSound, properties: AudioProperties) {
22        let sink = Sink::new(&self.device);
23        let source = Decoder::new(Cursor::new(sound.bytes))
24            .unwrap()
25            .amplify(properties.volume);
26        sink.append(source);
27        sink.detach();
28    }
29}
30
31#[derive(Clone)]
32pub struct NativeSound {
33    bytes: &'static [u8],
34}
35
36impl NativeSound {
37    pub fn new(bytes: &'static [u8]) -> Self {
38        Self { bytes }
39    }
40}
41
42impl AudioPlayer for NativeAudioPlayer {
43    type Sound = NativeSound;
44    fn play(&self, sound: &Self::Sound, properties: AudioProperties) {
45        NativeAudioPlayer::play(self, sound, properties)
46    }
47    fn load_sound(&self, bytes: &'static [u8]) -> Self::Sound {
48        NativeSound::new(bytes)
49    }
50}