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