general_audio/
lib.rs

1pub trait AudioPlayer {
2    type Sound;
3    type Handle: AudioHandle;
4    #[must_use]
5    fn play(&self, sound: &Self::Sound) -> Self::Handle;
6    #[must_use]
7    fn play_loop(&self, sound: &Self::Sound) -> Self::Handle;
8    fn load_sound(&self, bytes: &'static [u8]) -> Self::Sound;
9}
10
11pub trait AudioHandle {
12    fn set_volume(&self, volume: f32);
13    fn volume(&self) -> f32;
14    fn pause(&self);
15    fn play(&self);
16    fn background(self);
17}
18
19impl<A: AudioPlayer> AudioPlayer for Option<A> {
20    type Sound = Option<A::Sound>;
21    type Handle = Option<A::Handle>;
22    fn play(&self, sound: &Self::Sound) -> Self::Handle {
23        self.as_ref().and_then(|a| sound.as_ref().map(|s| a.play(s)))
24    }
25    fn play_loop(&self, sound: &Self::Sound) -> Self::Handle {
26        self.as_ref().and_then(|a| sound.as_ref().map(|s| a.play_loop(s)))
27    }
28    fn load_sound(&self, bytes: &'static [u8]) -> Self::Sound {
29        self.as_ref().map(|a| a.load_sound(bytes))
30    }
31}
32
33impl<H: AudioHandle> AudioHandle for Option<H> {
34    fn set_volume(&self, volume: f32) {
35        if let Some(handle) = self.as_ref() {
36            handle.set_volume(volume);
37        }
38    }
39    fn volume(&self) -> f32 {
40        if let Some(handle) = self.as_ref() {
41            handle.volume()
42        } else {
43            0.0
44        }
45    }
46    fn pause(&self) {
47        if let Some(handle) = self.as_ref() {
48            handle.pause();
49        }
50    }
51    fn play(&self) {
52        if let Some(handle) = self.as_ref() {
53            handle.play();
54        }
55    }
56    fn background(self) {
57        if let Some(handle) = self {
58            handle.background()
59        }
60    }
61}