iOS MPMoviePlayerController在后台播放音频

时间:2013-03-21 06:18:39

标签: iphone ios mpmovieplayercontroller multitasking background-audio

我有MPMoviePlayerController应该在后台播放视频的音频,应该由多任务播放/暂停控件控制。

使用Required background modes更新.plist文件并调用以下内容:

- (void)startBackgroundStreaming
{
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];

    NSError *activationError = nil;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:&activationError];
    [audioSession setActive:YES error:&activationError];

}

应用程序图标出现在多任务播放/暂停栏中,但这些按钮不响应。

谢谢!

1 个答案:

答案 0 :(得分:8)

这个难题的缺失部分是处理您正在接收的遥控事件。您可以通过在应用程序委托中实现-(void)remoteControlReceivedWithEvent:(UIEvent *)event方法来完成此操作。最简单的形式如下:

-(void)remoteControlReceivedWithEvent:(UIEvent *)event{
    if (event.type == UIEventTypeRemoteControl){
        switch (event.subtype) {
            case UIEventSubtypeRemoteControlTogglePlayPause:
                // Toggle play pause
                break;
            default:
                break;
        }
    }
}

但是,在应用程序委托上调用此方法,但您始终可以将事件作为对象发布通知,以便拥有影片播放器控制器的视图控制器可以获取事件,如下所示:

-(void)remoteControlReceivedWithEvent:(UIEvent *)event{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"RemoteControlEventReceived" object:event];
}

然后在您分配给通知的侦听器方法中获取事件对象。

-(void)remoteControlEventNotification:(NSNotification *)note{
    UIEvent *event = note.object;
    if (event.type == UIEventTypeRemoteControl){
        switch (event.subtype) {
            case UIEventSubtypeRemoteControlTogglePlayPause:
                if (_moviePlayerController.playbackState == MPMoviePlaybackStatePlaying){
                    [_moviePlayerController pause];
                } else {
                    [_moviePlayerController play];
                }
                break;
                // You get the idea.
            default:
                break;
        }
    }
}