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
50
51
52
53
54
55
56
57
58
59
60
61
pub trait AudioPlayer {
    type Sound;
    type Handle: AudioHandle;
    #[must_use]
    fn play(&self, sound: &Self::Sound) -> Self::Handle;
    #[must_use]
    fn play_loop(&self, sound: &Self::Sound) -> Self::Handle;
    fn load_sound(&self, bytes: &'static [u8]) -> Self::Sound;
}

pub trait AudioHandle {
    fn set_volume(&self, volume: f32);
    fn volume(&self) -> f32;
    fn pause(&self);
    fn play(&self);
    fn background(self);
}

impl<A: AudioPlayer> AudioPlayer for Option<A> {
    type Sound = Option<A::Sound>;
    type Handle = Option<A::Handle>;
    fn play(&self, sound: &Self::Sound) -> Self::Handle {
        self.as_ref().and_then(|a| sound.as_ref().map(|s| a.play(s)))
    }
    fn play_loop(&self, sound: &Self::Sound) -> Self::Handle {
        self.as_ref().and_then(|a| sound.as_ref().map(|s| a.play_loop(s)))
    }
    fn load_sound(&self, bytes: &'static [u8]) -> Self::Sound {
        self.as_ref().map(|a| a.load_sound(bytes))
    }
}

impl<H: AudioHandle> AudioHandle for Option<H> {
    fn set_volume(&self, volume: f32) {
        if let Some(handle) = self.as_ref() {
            handle.set_volume(volume);
        }
    }
    fn volume(&self) -> f32 {
        if let Some(handle) = self.as_ref() {
            handle.volume()
        } else {
            0.0
        }
    }
    fn pause(&self) {
        if let Some(handle) = self.as_ref() {
            handle.pause();
        }
    }
    fn play(&self) {
        if let Some(handle) = self.as_ref() {
            handle.play();
        }
    }
    fn background(self) {
        if let Some(handle) = self {
            handle.background()
        }
    }
}