且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iOS MPMoviePlayerController在后台播放音频

更新时间:2023-09-22 09:19:16

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

The missing piece of the puzzle is handling the remote control events you are receiving. You do this by implementing the -(void)remoteControlReceivedWithEvent:(UIEvent *)event method in your application delegate. In its simplest form it would look like:

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

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

However this method is called on the application delegate, but you can always post a notification with the event as the object so that the view controller that owns the movie player controller can get the event, like so:

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

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

Then grab the event object in the listener method you assign to the notification.

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