AVAudioPlayer在后台播放文件

时间:2011-11-01 10:55:46

标签: iphone objective-c avaudioplayer

我正在开发应用程序应该在后台运行的音乐应用程序。

那是用户选择要播放的文件,然后按下主页按钮 那么文件应该继续在后台播放。

我正在使用AVAudioPlayer。

我试过了:

**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;
    }
}
}

0 个答案:

没有答案