use std::fmt::{self, Debug, Formatter};
use std::path::Path;
use std::sync::Arc;
use crate::error::Result;
use crate::fs;
use crate::platform::AudioControls;
use crate::Context;
#[derive(Debug, Clone, PartialEq)]
pub struct Sound {
pub(crate) data: Arc<[u8]>,
}
impl Sound {
pub fn new<P>(path: P) -> Result<Sound>
where
P: AsRef<Path>,
{
Ok(Sound {
data: fs::read(path)?.into(),
})
}
pub fn from_file_data(data: &[u8]) -> Sound {
Sound { data: data.into() }
}
pub fn play(&self, ctx: &Context) -> Result<SoundInstance> {
ctx.audio
.play_sound(Arc::clone(&self.data), true, false, 1.0, 1.0)
.map(|controls| SoundInstance { controls })
}
pub fn repeat(&self, ctx: &Context) -> Result<SoundInstance> {
ctx.audio
.play_sound(Arc::clone(&self.data), true, true, 1.0, 1.0)
.map(|controls| SoundInstance { controls })
}
pub fn spawn(&self, ctx: &Context) -> Result<SoundInstance> {
ctx.audio
.play_sound(Arc::clone(&self.data), false, false, 1.0, 1.0)
.map(|controls| SoundInstance { controls })
}
pub fn play_with(&self, ctx: &Context, volume: f32, speed: f32) -> Result<SoundInstance> {
ctx.audio
.play_sound(Arc::clone(&self.data), true, false, volume, speed)
.map(|controls| SoundInstance { controls })
}
pub fn repeat_with(&self, ctx: &Context, volume: f32, speed: f32) -> Result<SoundInstance> {
ctx.audio
.play_sound(Arc::clone(&self.data), true, true, volume, speed)
.map(|controls| SoundInstance { controls })
}
pub fn spawn_with(&self, ctx: &Context, volume: f32, speed: f32) -> Result<SoundInstance> {
ctx.audio
.play_sound(Arc::clone(&self.data), false, false, volume, speed)
.map(|controls| SoundInstance { controls })
}
}
#[derive(Clone)]
pub struct SoundInstance {
pub(crate) controls: Arc<AudioControls>,
}
impl SoundInstance {
pub fn play(&self) {
self.controls.play();
}
pub fn stop(&self) {
self.controls.stop();
}
pub fn pause(&self) {
self.controls.pause();
}
pub fn set_volume(&self, volume: f32) {
self.controls.set_volume(volume);
}
pub fn set_speed(&self, speed: f32) {
self.controls.set_speed(speed);
}
pub fn set_repeating(&self, repeating: bool) {
self.controls.set_repeating(repeating);
}
pub fn toggle_repeating(&self) {
self.controls.set_repeating(!self.controls.repeating());
}
}
impl Debug for SoundInstance {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("SoundInstance")
.field("controls", &"<platform internals>")
.finish()
}
}
pub fn set_master_volume(ctx: &mut Context, volume: f32) {
ctx.audio.set_master_volume(volume);
}
pub fn get_master_volume(ctx: &mut Context) -> f32 {
ctx.audio.master_volume()
}