This implements a proof-of-concept for an improved audio frontend. The largest change is the introduction of events and event handling: both by time elapsed and by track events, such as ending or looping. Following on from this, the library now includes a basic, event-driven track queue system (which people seem to ask for unusually often). A new sample, `examples/13_voice_events`, demonstrates both the `TrackQueue` system and some basic events via the `~queue` and `~play_fade` commands. Locks are removed from around the control of `Audio` objects, which should allow the backend to be moved to a more granular futures-based backend solution in a cleaner way.
42 lines
1.5 KiB
Rust
42 lines
1.5 KiB
Rust
//! Utility methods for seeking or decoding.
|
|
|
|
use crate::constants::*;
|
|
use audiopus::{coder::Decoder, Channels, Result as OpusResult, SampleRate};
|
|
use std::{mem, time::Duration};
|
|
|
|
/// Calculates the sample position in a FloatPCM stream from a timestamp.
|
|
pub fn timestamp_to_sample_count(timestamp: Duration, stereo: bool) -> usize {
|
|
((timestamp.as_millis() as usize) * (MONO_FRAME_SIZE / FRAME_LEN_MS)) << stereo as usize
|
|
}
|
|
|
|
/// Calculates the time position in a FloatPCM stream from a sample index.
|
|
pub fn sample_count_to_timestamp(amt: usize, stereo: bool) -> Duration {
|
|
Duration::from_millis((((amt * FRAME_LEN_MS) / MONO_FRAME_SIZE) as u64) >> stereo as u64)
|
|
}
|
|
|
|
/// Calculates the byte position in a FloatPCM stream from a timestamp.
|
|
///
|
|
/// Each sample is sized by `mem::size_of::<f32>() == 4usize`.
|
|
pub fn timestamp_to_byte_count(timestamp: Duration, stereo: bool) -> usize {
|
|
timestamp_to_sample_count(timestamp, stereo) * mem::size_of::<f32>()
|
|
}
|
|
|
|
/// Calculates the time position in a FloatPCM stream from a byte index.
|
|
///
|
|
/// Each sample is sized by `mem::size_of::<f32>() == 4usize`.
|
|
pub fn byte_count_to_timestamp(amt: usize, stereo: bool) -> Duration {
|
|
sample_count_to_timestamp(amt / mem::size_of::<f32>(), stereo)
|
|
}
|
|
|
|
/// Create an Opus decoder outputting at a sample rate of 48kHz.
|
|
pub fn decoder(stereo: bool) -> OpusResult<Decoder> {
|
|
Decoder::new(
|
|
SampleRate::Hz48000,
|
|
if stereo {
|
|
Channels::Stereo
|
|
} else {
|
|
Channels::Mono
|
|
},
|
|
)
|
|
}
|