veloren/voxygen/src/audio/soundcache.rs

54 lines
1.2 KiB
Rust
Raw Normal View History

2019-09-05 09:11:18 +00:00
use common::assets;
use hashbrown::HashMap;
2019-09-05 09:11:18 +00:00
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
2019-09-05 09:11:18 +00:00
pub struct Sound(Arc<Vec<u8>>);
impl AsRef<[u8]> for Sound {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
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)))
}
pub fn cursor(&self) -> io::Cursor<Sound> {
io::Cursor::new(Sound(self.0.clone()))
}
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(),
}
}
pub fn load_sound(&mut self, name: String) -> rodio::Decoder<io::Cursor<Sound>> {
self.sounds
.entry(name.clone())
.or_insert(Sound::load(&name).unwrap())
.decoder()
}
}