Reputation:

Make AVFoundation framework not fading when screen fades

I am implementing some audiobooks for iPhone. I used AVFoundation. Something like this:

NSString *path = [[NSBundle mainBundle] pathForResource:@"intro" ofType:@"mp3"];
        player=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

I have a problem. When the screen goes dark (single audio files can be very long) the audio stops playing.

I solved this problem with this string of code

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    // something else here...

    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];

}

This does not allow the iPhone to "sleep". However you can guess how this is foolish: your battery level goes down in minutes and this is not possible by audiobooks lasting more than 20 hours, for example...

So, do you know a way to prevent that when the screen sleeps the AVAudioPlayer does not stop playing?

Thanks... Fabio

Upvotes: 1

Views: 444

Answers (2)

Gordon Childs
Gordon Childs

Reputation: 36072

Set your audio session to kAudioSessionCategory_MediaPlayback to playback while the screen is locked.

Upvotes: 2

John Ballinger
John Ballinger

Reputation: 7540

Could I suggest that once you start playing the audio file that you tell the user to press the power button (not home button) which will lock the phone. It will not close you app but it will power off the screen with you application running in the background. Currently several apps do this.

Upvotes: 0

Related Questions