optimizationrustaudiorodio

50ms delay when returning from a function in rust


I apologise for my ineptitude, I am fairly new to rust and I have only been using it for a few weeks

I have this code:

fn main() {
    notes.push(note_array[24]);
    let now = output::play_oscillator(&patch, &notes, 1000);
let elapsed = now.elapsed().as_millis();
    println!("Elapsed: {:.2?}", elapsed);
    notes.clear();
}

And the play_oscillator() fn is as follows:

#[inline]
pub fn play_oscillator(patch: &SynthPatch, notes: &Vec<Note>, duration: u64) -> Instant {
    
    let (_stream, stream_handle) = OutputStream::try_default().unwrap();

    for i in 0..notes.len() {
        let mut oscillator = WavetableOscillator::new(patch.oscillator_type.sample_rate.clone(), patch.oscillator_type.wave_table.clone());
        oscillator.set_frequency(notes[i].frequency);
        let oscillator = filter_processor::apply_filter(oscillator, &patch.filter);
        let oscillator = oscillator.convert_samples::<f32>();
        let oscillator = stream_handle.play_raw(oscillator);
        let _result: &Result<(), PlayError> = &oscillator;
    }

    std::thread::sleep(std::time::Duration::from_millis(duration));

    let now = Instant::now();
    now
}

For some reason, the elapsed time between the end of play_oscillator() and the line where i print the elapsed time is 50ms, despite the fact that no code is being run here.

I have moved let now = Instant::now() to the main() line after where play_oscillator() is used and the elapsed time is suddenly 0ms, even though no code is actually being run between the end of play_oscillator() and the line after where it is called.

Could someone please explain where this delay is coming from?


Solution

  • I solved the problem by using a more efficient audio handler within the Rodio crate. I used sink rather than play_raw(), thus removing the need to drop _stream and stream_handle at the end of play_oscillator() every time as this was causing the delay.