use common::assets; use hashbrown::HashMap; use rodio; use std::convert::AsRef; use std::io; use std::io::Read; use std::sync::Arc; // Implementation of sound taken from this github issue: // https://github.com/RustAudio/rodio/issues/141 pub struct Sound(Arc>); impl AsRef<[u8]> for Sound { fn as_ref(&self) -> &[u8] { &self.0 } } impl Sound { pub fn load(filename: &str) -> Result { let mut file = assets::load_file(filename, &["wav"])?; let mut buf = Vec::new(); file.read_to_end(&mut buf)?; Ok(Sound(Arc::new(buf))) } pub fn cursor(&self) -> io::Cursor { io::Cursor::new(Sound(self.0.clone())) } pub fn decoder(&self) -> rodio::Decoder> { rodio::Decoder::new(self.cursor()).unwrap() } } pub struct SoundCache { sounds: HashMap, } impl SoundCache { pub fn new() -> Self { Self { sounds: HashMap::new(), } } pub fn load_sound(&mut self, name: &str) -> rodio::Decoder> { self.sounds .entry(name.to_string()) .or_insert(Sound::load(name).unwrap()) .decoder() } }