Duration more or less works again

This commit is contained in:
Pierre Krieger 2015-10-16 15:25:55 +02:00
parent efc00ff834
commit e2fc982652
2 changed files with 20 additions and 14 deletions

View file

@ -140,9 +140,19 @@ pub struct Handle<'a> {
}
impl<'a> Handle<'a> {
#[inline]
pub fn append<S>(&self, source: S) where S: Source + Send + 'static, S::Item: Sample + Clone + Send {
if let Some(duration) = source.get_total_duration() {
let duration = duration.as_secs() as usize * 1000 +
duration.subsec_nanos() as usize / 1000000;
self.remaining_duration_ms.fetch_add(duration, Ordering::Relaxed);
} else {
let duration = source.size_hint().0 * 1000 / (source.get_samples_rate() as usize *
source.get_channels() as usize);
self.remaining_duration_ms.fetch_add(duration, Ordering::Relaxed);
}
let source = UniformSourceIterator::new(source, self.channels, self.samples_rate);
let source = Box::new(source);
self.next_sounds.lock().unwrap().push(source);
@ -164,11 +174,6 @@ impl<'a> Handle<'a> {
}
}
#[inline]
pub fn get_total_duration_ms(&self) -> u32 {
unimplemented!()
}
#[inline]
pub fn get_remaining_duration_ms(&self) -> u32 {
self.remaining_duration_ms.load(Ordering::Relaxed) as u32
@ -276,6 +281,7 @@ fn background(rx: Receiver<Command>) {
// updating the contents of `remaining_duration_ms`
for &(ref decoder, ref remaining_duration_ms, _) in sounds.iter() {
let (num_samples, _) = decoder.size_hint();
// TODO: differenciate sounds from this sink from sounds from other sinks
let num_samples = num_samples + voice.get_pending_samples();
let value = (num_samples as u64 * 1000 / (voice.get_channels() as u64 *
voice.get_samples_rate().0 as u64)) as u32;
@ -319,6 +325,9 @@ impl Iterator for QueueIterator {
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(self.current.size_hint().0, None)
// TODO: slow? benchmark this
let next_hints = self.next.lock().unwrap().iter()
.map(|i| i.size_hint().0).fold(0, |a, b| a + b);
(self.current.size_hint().0 + next_hints, None)
}
}

View file

@ -58,13 +58,9 @@ impl Sink {
self.0.stop()
}
/// Returns the number of milliseconds in total in the sound file.
#[inline]
pub fn get_total_duration_ms(&self) -> u32 {
self.0.get_total_duration_ms()
}
/// Returns the number of milliseconds remaining before the end of the sound.
/// Returns the minimum number of milliseconds remaining before the end of the sound.
///
/// Note that this is a minimum value, and the sound can last longer.
#[inline]
pub fn get_remaining_duration_ms(&self) -> u32 {
self.0.get_remaining_duration_ms()
@ -73,6 +69,7 @@ impl Sink {
/// Sleeps the current thread until the sound ends.
#[inline]
pub fn sleep_until_end(&self) {
// TODO: sleep repeatidely until the sound is finished (see the docs of `get_remaining_duration`)
thread::sleep_ms(self.get_remaining_duration_ms());
}
}