Joe Völker
Joe Völker

Reputation: 791

Can I use a loop to delay app going to background?

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.

Upvotes: 1

Views: 298

Answers (2)

hotpaw2
hotpaw2

Reputation: 70673

Blocking the UI run loop this way is not a good app design. The OS may even kill your app if you block the run loop for too long.

One possibility is to register your app for multitasking background audio play, and, while in the background, play a couple seconds of audio taper to zero before stopping the audio and releasing the audio session.

Upvotes: 4

lbrndnr
lbrndnr

Reputation: 3389

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.

Upvotes: 1

Related Questions