Search code examples
iosnstimermpmusicplayercontroller

Sleep Timer with MPMusicPlayerController


I'm working on an iOS app that uses MPMusicPlayerController to play audio from the iTunes library.

Is it possible to create a timer that will run while the app is in the background? I would like to implement a sleep timer. NSTimer seems like it is out of the question, or rather limited to 3 minutes. Are there any other options I could try?

Currently, I have this in my App Delegate.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                     withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                           error:nil];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    return YES;
}

Solution

  • To keep the app running in the background while using MPMusicPlayerController you can play silence in the background. This is probably a bad idea...

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        // Override point for customization after application launch.
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                         withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                               error:nil];
        [[AVAudioSession sharedInstance] setActive:YES error:nil];
        NSString* path = [[NSBundle mainBundle] pathForResource:@"silence" ofType:@"m4a"];
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:path] error:nil];
        self.player.numberOfLoops = -1;
        [self.player play];
    
        return YES;
    }