use bevy::asset::io::Reader;
use bevy::asset::{AssetLoader, AsyncReadExt, LoadContext};
use kira::sound::static_sound::StaticSoundSettings;
use kira::sound::streaming::StreamingSoundSettings;
use kira::sound::FromFileError;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::sources::audio_file::source::AudioFile;
#[derive(Default)]
pub struct AudioFileLoader;
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum AudioFileLoaderError {
#[error("Could not read the file: {0}")]
Io(#[from] std::io::Error),
#[error("Error while loading a sound: {0}")]
FileError(#[from] FromFileError),
}
#[derive(Debug, Copy, Clone, Deserialize, Serialize, Default)]
pub struct AudioAssetSettings {
pub should_stream: bool,
}
impl AssetLoader for AudioFileLoader {
type Asset = AudioFile;
type Settings = AudioAssetSettings;
type Error = AudioFileLoaderError;
async fn load<'a>(
&'a self,
reader: &'a mut Reader<'_>,
settings: &'a AudioAssetSettings,
load_context: &'a mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
if settings.should_stream {
Ok(AudioFile::Streaming {
path: load_context.path().to_path_buf(),
settings: StreamingSoundSettings::new(),
})
} else {
let mut sound_bytes = vec![];
reader.read_to_end(&mut sound_bytes).await?;
Ok(AudioFile::Static(
sound_bytes.into(),
StaticSoundSettings::default(),
))
}
}
fn extensions(&self) -> &[&str] {
&["wav", "flac", "mp3", "ogg", "oga", "spx"]
}
}