RustAudio / cpal

Cross-platform audio I/O library in pure Rust

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Why is thread sleeping needed for stream.play() to stream audio ?

JulienH2000 opened this issue · comments

Hello,
In all the repo examples, the streaming is achieved via making sleep the thread where device.build_output_stream() and stream.play() are. As it avoid the thread to break and define the audio stream duration.
Relying to a thread::sleep is problematic for many reasons, and I struggle to understand how to achieve a not duration-defined audio stream, in the most elegant and "cpal" way.
What comes to mind is encapsulating the stream into a thread::spawn(loop { //stream output instance }). But it gives me a hard time to implement due to lifetime and borrowing issues with shared values (devices config infos, oscillators settings, etc...)
Is there a "best-practice" way to run a stream without any duration parameter ? And especially without relying on thread sleep ?
thanks a lot.
You can find my implementation at https://github.com/JulienH2000/audio_test/tree/live_threading

Sleeping is not needed, but the stream has to kept alive to keep playing. You can not let it go out of scope or it will be dropped and stop playing. So as long as you don’t let it go out of scope you’re OK. The easiest way (if you don’t have anything else going on) is sleeping for as long as you want to the stream to play.

Ok ! Just tried to hold the stream using a basic get user input function, works like a charm ! So the key is holding the stream.play() in scope ?
Thanks a lot ! I have to admit that build_output_stream method works weird for someone not used to advanced programming concepts (me lol), suce as the callback way of buffering data, or the way that all the stream buffering is written for one sample, but holding it in scope makes it buffer sample to next sample..
Your answer definitely unlocked something in my head about the output streaming sequence ! Thanks !!