iOS MPMoviePlayerController在后台播放音频

问题描述:

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

更新的.plist文件,Required background modes并调用后,以下:

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

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

}

的应用程序图标显示在多任务播放/暂停吧,但这些按钮没反应。

谢谢!

拼图的缺失部分是处理您收到的遥控器事件。您可以通过在您的应用程序委托中实施-(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; 
     } 
    } 
} 
+1

可以从View Controller调用 - (void)remoteControlReceivedWithEvent:(UIEvent *)事件,而不是AppDelegate – khunshan 2014-08-06 11:43:24