AVAudioPlayer play file in Background

Deadly 提交于 2019-12-20 02:56:22

问题


I am developing music app in which app should be run in background.

That is when user select file to play and he pressed home button then file should continue to play in background.

I am using AVAudioPlayer.

I tried this:

**AppDelegate.m**


- (void)applicationDidEnterBackground:(UIApplication *)application {
UIApplication* app = [UIApplication sharedApplication];

NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil);

bgTask = [app beginBackgroundTaskWithExpirationHandler: ^{
    dispatch_async(dispatch_get_main_queue(), ^{
        [app endBackgroundTask:self->bgTask];
        self->bgTask = UIBackgroundTaskInvalid;
    });
}];

dispatch_async(dispatch_get_main_queue(), ^{
    self->bgTask = UIBackgroundTaskInvalid;
});

}

**Player.m**

- (void) viewDidAppear:(BOOL)animated {
NSLog(@"viewDidAppear");
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];

}

-(BOOL)canBecomeFirstResponder{ 
NSLog(@"canBecomeFirstResponder");
return YES; 
} 

-(void)viewWillDisappear:(BOOL)animated{
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
[super viewWillDisappear:animated];
}

- (void)remoteControlReceivedWithEvent:(UIEvent*)receivedEvent{

NSLog(@"remoteControlReceivedWithEvent");

if (receivedEvent.type == UIEventTypeRemoteControl){
    switch (receivedEvent.subtype){
        case UIEventSubtypeRemoteControlTogglePlayPause:
            NSLog(@"UIEventSubtypeRemoteControlTogglePlayPause");
            break;
        case UIEventSubtypeRemoteControlPreviousTrack:
            NSLog(@"UIEventSubtypeRemoteControlPreviousTrack");
            break;
        case UIEventSubtypeRemoteControlNextTrack:
            break;
        default:
            break;
    }
}
}

来源:https://stackoverflow.com/questions/7965419/avaudioplayer-play-file-in-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!