My iPhone app plays audio and needs to gently fade out when the user hits the home button (thus sending the app to the background). I can make my audio unit fade out, but, unfortunately, since the app gets sent to background before, the sound ending with a brute crackle.
That means, I need to delay going to background. I could check the AUs amplitude in a loop and exit the loop when the amplitude reaches zero. To be double safe, I rigged up an alarm so that the delay will never exceed 1/10 of a second. Specifically, in my AppDelegate’s applicationDidEnterBackground method, I say:
time_t s1 = clock() + (time_t)(0.1 * CLOCKS_PER_SEC);
while( ([sinus current_amplitude] > 0.0 ) && ( s1 > clock()) );
This works as expected, but stalls the app. Is this considered bad style, or is it OK?
Followup: Thanks for the input. I’ve stuck to delaying instead of continuing to play in the background, but now I’m doing it like this:
NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.1 ];
[NSThread sleepUntilDate:future];
which is much more elegant.
It isn’t the default behavior of an app which plays music. You should let your app terminate as normal but fade out the music as you want. It can also play a few seconds in the background.