2019-09-05 09:11:18 +00:00
|
|
|
use common::assets;
|
2019-09-01 23:00:12 +00:00
|
|
|
use hashbrown::HashMap;
|
2019-09-05 09:11:18 +00:00
|
|
|
use rodio;
|
2020-02-01 20:39:39 +00:00
|
|
|
use std::{convert::AsRef, io, io::Read, sync::Arc};
|
2019-09-01 23:00:12 +00:00
|
|
|
|
|
|
|
// Implementation of sound taken from this github issue:
|
|
|
|
// https://github.com/RustAudio/rodio/issues/141
|
2019-09-05 09:11:18 +00:00
|
|
|
pub struct Sound(Arc<Vec<u8>>);
|
2019-09-01 23:00:12 +00:00
|
|
|
|
|
|
|
impl AsRef<[u8]> for Sound {
|
2020-02-01 20:39:39 +00:00
|
|
|
fn as_ref(&self) -> &[u8] { &self.0 }
|
2019-09-01 23:00:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Sound {
|
|
|
|
pub fn load(filename: &str) -> Result<Sound, assets::Error> {
|
|
|
|
let mut file = assets::load_file(filename, &["wav"])?;
|
|
|
|
let mut buf = Vec::new();
|
|
|
|
file.read_to_end(&mut buf)?;
|
|
|
|
Ok(Sound(Arc::new(buf)))
|
|
|
|
}
|
|
|
|
|
2020-02-01 20:39:39 +00:00
|
|
|
pub fn cursor(&self) -> io::Cursor<Sound> { io::Cursor::new(Sound(self.0.clone())) }
|
2019-09-01 23:00:12 +00:00
|
|
|
|
|
|
|
pub fn decoder(&self) -> rodio::Decoder<io::Cursor<Sound>> {
|
|
|
|
rodio::Decoder::new(self.cursor()).unwrap()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct SoundCache {
|
|
|
|
sounds: HashMap<String, Sound>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl SoundCache {
|
|
|
|
pub fn new() -> Self {
|
|
|
|
Self {
|
2019-09-05 09:11:18 +00:00
|
|
|
sounds: HashMap::new(),
|
2019-09-01 23:00:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-06 10:36:42 +00:00
|
|
|
pub fn load_sound(&mut self, name: &str) -> rodio::Decoder<io::Cursor<Sound>> {
|
2019-09-01 23:00:12 +00:00
|
|
|
self.sounds
|
2019-09-06 10:36:42 +00:00
|
|
|
.entry(name.to_string())
|
|
|
|
.or_insert(Sound::load(name).unwrap())
|
2019-09-01 23:00:12 +00:00
|
|
|
.decoder()
|
|
|
|
}
|
|
|
|
}
|