andelf / rust-sdl2_mixer

Rust bindings for sdl2_mixer
Apache License 2.0
13 stars 17 forks source link

how should i play sounds in the background? #39

Open DanielCollins opened 8 years ago

DanielCollins commented 8 years ago

i have a sound playing, but only if i use an sdl timer to block. do i have to manage a thread for each sound?

DanielCollins commented 8 years ago

i think that they do play in the background if i follow the call to play with loop { }, it might be some interaction with my glutin main loop that is causing issues. i'm a bit confused

MarkDDR commented 8 years ago

You don't need to block a thread to play a sound. When you do sound.play(1), the sound will just play in the background. If you wanted to wait until a sound is done playing, then you would want to do something like

sound.play(1);
while sound.is_playing() {
    timer.delay(1000); // so you don't use your entire cpu. Change delay as you want
}
DanielCollins commented 8 years ago

You are right, sound.play(1) does play in the background correctly.

My mistake was that it worked fine in main() but then when I cut and paste those lines into a function I didn't get any output (which to me sounds like something which should be impossible to result in different behaviour which is why I was getting so confused and looking for unrelated problems).

I assume the reason it doesn't work is that when I move it to a function, the result of sdl2_mixer::Music::from_file goes out of scope and gets cleaned up before playback is finished because it is now a local.

I'm assuming that it's my fault and rust/ rust-sdl2_mixer just wants me to be responsible for controlling my lifetimes properly.

But it kind of sucked to diagnose and I'm used to rust yelling at me when I make mistakes like this, rather than failing silently. So before I close the issue, is there any possibility that this could be made easier? Is it possible to change the API so that it automatically tracks which sounds need to be live? Or, at least, would it be possible to make it fail loudly rather than silently? I'm not familiar enough with rust to know how this is supposed to go.