use crate::Sound;
use super::{SetPaused, SetVolume};
pub trait SetSpeed {
fn set_speed(&mut self, multiplier: f32);
}
pub struct AdjustableSpeed<S: Sound> {
inner: S,
speed_adjustment: f32,
speed_changed: bool,
}
impl<S> AdjustableSpeed<S>
where
S: Sound,
{
pub fn new(inner: S) -> Self {
Self::new_with_speed(inner, 1.0)
}
pub fn new_with_speed(inner: S, speed_adjustment: f32) -> Self {
AdjustableSpeed {
inner,
speed_adjustment,
speed_changed: false,
}
}
pub fn inner(&self) -> &S {
&self.inner
}
pub fn inner_mut(&mut self) -> &mut S {
&mut self.inner
}
pub fn into_inner(self) -> S {
self.inner
}
}
impl<S> Sound for AdjustableSpeed<S>
where
S: Sound,
{
fn channel_count(&self) -> u16 {
self.inner.channel_count()
}
fn sample_rate(&self) -> u32 {
let new_rate = (self.inner.sample_rate() as f32 * self.speed_adjustment).round() as u32;
u32::max(1, new_rate)
}
fn next_sample(&mut self) -> Result<crate::NextSample, crate::Error> {
if self.speed_changed {
self.speed_changed = false;
return Ok(crate::NextSample::MetadataChanged);
}
self.inner.next_sample()
}
fn on_start_of_batch(&mut self) {
self.inner.on_start_of_batch()
}
}
impl<S> SetSpeed for AdjustableSpeed<S>
where
S: Sound,
{
fn set_speed(&mut self, new: f32) {
self.speed_changed = true;
self.speed_adjustment = new;
}
}
impl<S> AdjustableSpeed<S>
where
S: Sound,
{
pub fn speed(&self) -> f32 {
self.speed_adjustment
}
}
impl<S> SetPaused for AdjustableSpeed<S>
where
S: Sound + SetPaused,
{
fn set_paused(&mut self, paused: bool) {
self.inner.set_paused(paused)
}
}
impl<S> SetVolume for AdjustableSpeed<S>
where
S: Sound + SetVolume,
{
fn set_volume(&mut self, multiplier: f32) {
self.inner.set_volume(multiplier)
}
}
#[cfg(test)]
#[path = "./tests/adjustable_speed.rs"]
mod tests;