Skip to content

Commit

Permalink
Merge pull request #14 from barafael/feet/impl_playable_for_pitch_and…
Browse files Browse the repository at this point in the history
…_note

Implement `Playable` for `HasFrequency`
  • Loading branch information
twitchax committed Jun 12, 2023
2 parents 81e8565 + 8318d99 commit b7693cb
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/core/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,19 @@ impl PlaybackHandle {
}

/// A trait for types that can be "played" via the system's audio output.
/// ```rust, no_run
/// use std::time::Duration;
///
/// use klib::core::base::Playable;
/// use klib::core::{named_pitch::NamedPitch, note::Note, octave::Octave};
///
/// let handle = Note::new(NamedPitch::A, Octave::Four).play(
/// Duration::ZERO,
/// Duration::from_secs(1),
/// Duration::ZERO,
/// );
/// std::thread::sleep(Duration::from_secs(1));
/// ```
pub trait Playable {
/// Plays the [`Playable`].
#[must_use = "Dropping the PlayableResult will stop the playback."]
Expand Down
19 changes: 19 additions & 0 deletions src/core/pitch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

// Traits.

use std::time::Duration;

use once_cell::sync::Lazy;

use super::helpers::mel;
Expand Down Expand Up @@ -35,6 +37,23 @@ pub trait HasMel: HasFrequency {
}
}

#[cfg(feature = "audio")]
use super::base::{Playable, PlaybackHandle, Res};

#[cfg(feature = "audio")]
impl<T: HasFrequency> Playable for T {
fn play(&self, delay: Duration, length: Duration, fade_in: Duration) -> Res<PlaybackHandle> {
use rodio::{source::SineWave, OutputStream, Sink, Source};

let (stream, stream_handle) = OutputStream::try_default()?;
let sink = Sink::try_new(&stream_handle)?;
let source = SineWave::new(self.frequency()).take_duration(length - delay).buffered().delay(delay).fade_in(fade_in).amplify(0.20);
sink.append(source);

Ok(PlaybackHandle::new(stream, stream_handle, vec![sink]))
}
}

// Enum.

/// An enum representing the pitch of a note.
Expand Down

0 comments on commit b7693cb

Please sign in to comment.