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
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#[cfg(not(target_arch="wasm32"))]
extern crate rodio;


use asset::{Loadable, LoadingAsset};
#[cfg(target_arch="wasm32")]
use asset::LoadingHandle;
#[cfg(not(target_arch="wasm32"))]
use rodio::{Decoder, Sink, Source};
#[cfg(not(target_arch="wasm32"))]
use rodio::decoder::DecoderError;
#[cfg(not(target_arch="wasm32"))]
use rodio::source::{SamplesConverter, Amplify};
#[cfg(not(target_arch="wasm32"))]
use std::fs::File;
use std::path::Path;
#[cfg(not(target_arch="wasm32"))]
use std::io::{BufReader, Cursor, Error as IOError, Read};
#[cfg(not(target_arch="wasm32"))]
use std::sync::Arc;

#[cfg(target_arch="wasm32")]
extern "C" {
    fn load_sound(path: *mut i8) -> u32;
    fn play_sound(index: u32, volume: f32);
    fn set_music_track(index: u32);
    fn play_music();
    fn pause_music();
    fn get_music_volume() -> f32;
    fn set_music_volume(volume: f32);
}


#[derive(Clone)]
#[cfg(not(target_arch="wasm32"))]
pub struct Sound {
    val: Arc<Vec<u8>>,
    volume: f32
}

#[derive(Clone)]
#[cfg(target_arch="wasm32")]
pub struct Sound {
    index: u32,
    volume: f32
}


impl Sound {
    #[cfg(not(target_arch="wasm32"))]
    fn load_impl<P: AsRef<Path>>(path: P) -> Result<Sound, SoundError> {
        let mut bytes = Vec::new();
        BufReader::new(File::open(path)?).read_to_end(&mut bytes)?;
        let val = Arc::new(bytes);
        let sound = Sound {
            val,
            volume: 1f32
        };
        Decoder::new(Cursor::new(sound.clone()))?;
        Ok(sound)
    }
    
    #[cfg(target_arch="wasm32")]
    fn load_impl<P: AsRef<Path>>(path: P) -> u32 {
        use std::ffi::CString;
        unsafe { load_sound(CString::new(path.as_ref().to_str().unwrap()).unwrap().into_raw()) }
    }

    pub fn volume(&self) -> f32 {
        self.volume
    }

    pub fn set_volume(&mut self, volume: f32) {
        self.volume = volume;
    }

    #[cfg(not(target_arch="wasm32"))]
    fn get_source(&self) -> SamplesConverter<Amplify<Decoder<Cursor<Sound>>>, f32> {
        Decoder::new(Cursor::new(self.clone())).unwrap().amplify(self.volume).convert_samples()
    }


    #[cfg(not(target_arch="wasm32"))]
    #[allow(deprecated)]
    pub fn play(&self) {
        let endpoint = rodio::get_default_endpoint().unwrap();
        rodio::play_raw(&endpoint, self.get_source());
    }
    
    #[cfg(target_arch="wasm32")]
    pub fn play(&self) {
        unsafe { play_sound(self.index, self.volume); }
    }
}

impl Loadable for Sound {
    type Error = SoundError;

    #[cfg(not(target_arch="wasm32"))]
    fn load<P: AsRef<Path>>(path: P) -> LoadingAsset<Self> {
        match Sound::load_impl(path) {
            Ok(snd) => LoadingAsset::Loaded(snd),
            Err(err) => LoadingAsset::Errored(err)
        }
    }

    #[cfg(target_arch="wasm32")]
    fn load<P: AsRef<Path>>(path: P) -> LoadingAsset<Self> {
        LoadingAsset::Loading(LoadingHandle(Sound::load_impl(path)))
    }

    #[cfg(target_arch="wasm32")]
    fn parse_result(handle: LoadingHandle, loaded: bool, errored: bool) -> LoadingAsset<Self> {
        if loaded {
            if errored {
                LoadingAsset::Errored(SoundError::IOError)
            } else {
                LoadingAsset::Loaded(Sound {
                    index: handle.0,
                    volume: 1.0
                })
            }
        } else {
            LoadingAsset::Loading(handle)
        }
    }
}

#[cfg(not(target_arch="wasm32"))]
impl AsRef<[u8]> for Sound {
    fn as_ref(&self) -> &[u8] {
        self.val.as_ref().as_ref()
    }
}

#[cfg(not(target_arch="wasm32"))]
pub struct MusicPlayer {
    sink: Sink
}

#[cfg(target_arch="wasm32")]
pub struct MusicPlayer;

#[cfg(not(target_arch="wasm32"))]
impl MusicPlayer {
    #[allow(deprecated)]
    pub fn new() -> MusicPlayer {
        MusicPlayer {
            sink: Sink::new(&rodio::get_default_endpoint().unwrap())
        }
    }

    pub fn set_track(&mut self, sound: &Sound) {
        self.sink.stop();
        self.sink.append(sound.get_source().repeat_infinite());
    }

    pub fn play(&self) {
        self.sink.play();
    }


    pub fn pause(&self) {
        self.sink.pause();
    }
    
    pub fn finished(&self) -> bool {
        self.sink.empty()
    }

    pub fn volume(&self) -> f32 {
        self.sink.volume()
    }

    pub fn set_volume(&mut self, volume: f32) {
        self.sink.set_volume(volume);
    }
}

#[cfg(target_arch="wasm32")]
impl MusicPlayer {
    pub fn new() -> MusicPlayer { MusicPlayer }

    pub fn set_track(&mut self, sound: &Sound) {
        unsafe { set_music_track(sound.index) };
    }

    pub fn play(&self) {
        unsafe { play_music() };
    }


    pub fn pause(&self) {
        unsafe { pause_music() };
    }
    
    pub fn volume(&self) -> f32 {
        unsafe { get_music_volume() }
    }

    pub fn set_volume(&mut self, volume: f32) {
        unsafe { set_music_volume(volume) };
    }
}


#[derive(Clone, Debug)]
pub enum SoundError {
     UnrecognizedFormat,
     IOError
}

#[cfg(not(target_arch="wasm32"))]
impl From<DecoderError> for SoundError {
    fn from(err: DecoderError) -> SoundError {
        match err {
            DecoderError::UnrecognizedFormat => SoundError::UnrecognizedFormat
        }
    }
}

#[cfg(not(target_arch="wasm32"))]
impl From<IOError> for SoundError {
    fn from(_: IOError) -> SoundError {
        SoundError::IOError
    }
}