use std::collections::HashMap;
use std::path::Path;
use amethyst::assets::{AssetStorage, Loader};
use amethyst::audio::output::Output;
use amethyst::audio::{
AudioFormat,
AudioSink,
OggFormat,
Source,
SourceHandle,
};
use amethyst::ecs::World;
use regex::RegexBuilder;
const DEFAULT_VOLUME: f32 = 1.0;
#[derive(Default)]
pub struct AudioHandles {
source_handles: HashMap<String, SourceHandle>,
}
impl AudioHandles {
pub fn insert<T>(&mut self, name: T, handle: SourceHandle)
where
T: ToString,
{
self.source_handles.insert(name.to_string(), handle);
}
pub fn get<T>(&self, name: T) -> Option<SourceHandle>
where
T: ToString,
{
let name = name.to_string();
let err_msg =
format!("Given SourceHandle name cannot be empty: {}", name);
let name = name
.split("/")
.last()
.expect(&err_msg)
.split(".")
.next()
.expect(&err_msg);
self.source_handles.get(name).map(Clone::clone)
}
pub fn load<P>(&mut self, path: P, world: &World)
where
P: AsRef<Path>,
{
let path = path.as_ref();
if !path.is_file() {
panic!(format!(
"Given audio file path does not exist: '{:?}'",
path
));
}
let err_msg_match = format!(
"Given audio file path must match the pattern \
`/.+\\.(ogg|wav|mp3|flac)\\z/i`. Given: '{:?}'",
path
);
let filepath_regex = RegexBuilder::new(r".+\.(ogg|wav|mp3|flac)\z")
.case_insensitive(true)
.build()
.unwrap();
if filepath_regex.captures(path.to_str().unwrap()).is_some() {
let extension =
path.extension().expect(&err_msg_match).to_str().unwrap();
let extension_with_dot = format!(".{}", extension);
let name = path
.file_name()
.expect(&format!(
"Given path must lead to an audio file. Given: '{:?}'",
path
))
.to_str()
.unwrap()
.replace(&extension_with_dot, "");
let audio_format = match extension.to_lowercase().as_str() {
"ogg" => AudioFormat::Ogg,
"wav" => AudioFormat::Wav,
"mp3" => AudioFormat::Mp3,
"flac" => AudioFormat::Flac,
ext => panic!(format!(
"Given format is not supported for audio: '{:?}'",
ext
)),
};
let handle = {
let loader = world.read_resource::<Loader>();
loader.load(
path.to_str().unwrap(),
audio_format,
(),
(),
&world.read_resource(),
)
};
self.insert(name, handle);
} else {
panic!(err_msg_match)
}
}
pub fn get_or_load<P>(&mut self, path: P, world: &World) -> SourceHandle
where
P: AsRef<Path>,
{
let path = path.as_ref().to_str().unwrap();
if let Some(handle) = self.get(path) {
handle
} else {
self.load(path, world);
self.get(path).unwrap()
}
}
pub fn has_finished_loading_all(&self, world: &World) -> bool {
let asset = world.read_resource::<AssetStorage<Source>>();
self.source_handles
.values()
.all(|handle| asset.get(handle).is_some())
}
pub fn play<T>(&self, name: T, world: &World, volume: Option<f32>)
where
T: ToString,
{
let asset = world.read_resource::<AssetStorage<Source>>();
let output = world.read_resource::<Output>();
self.play_with(name, &asset, &output, volume);
}
pub fn play_with<T>(
&self,
name: T,
asset: &AssetStorage<Source>,
output: &Output,
volume: Option<f32>,
) where
T: ToString,
{
let handle = self.get(name.to_string()).expect(&format!(
"Audio SourceHandle with the given name doesn't exist: {}",
name.to_string()
));
if let Some(sound) = asset.get(&handle) {
output.play_once(sound, volume.unwrap_or(DEFAULT_VOLUME));
}
}
}