AVPlayerLayer在进入后台模式时停止播放

时间:2012-05-07 15:11:39

标签: iphone objective-c

我设置了AVPlayerLayer:

        audioPlayer = [[AVPlayer alloc]initWithURL:[NSURL fileURLWithPath:fileName]];
        avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:audioPlayer];
        [avPlayerLayer setFrame:self.view.bounds];
        [[self.view layer] addSublayer:avPlayerLayer];
        [audioPlayer play];

在AppDelegete中我添加:

[[AVAudioSession sharedInstance] setDelegate:self];    
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];

现在在UIViewController类我添加:

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

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlTogglePlayPause:
            if (audioPlayer.rate == 0.0) {
                [avPlayerLayer.player play];
            } else {
                [avPlayerLayer.player pause];
            }
            NSLog(@"4");
            break;
        case UIEventSubtypeRemoteControlPlay:
            [avPlayerLayer.player play];
            break;
        case UIEventSubtypeRemoteControlPause:
            [avPlayerLayer.player pause];
            NSLog(@"3");
            break;
        case UIEventSubtypeRemoteControlNextTrack:
            [self didPressNextSong:nil];
            NSLog(@"2");
            break;
        case UIEventSubtypeRemoteControlPreviousTrack:
            [self didPressLastSong:nil];
            NSLog(@"1");
            break;
        default:
            break;
    }
}

现在的问题是,当我移动到后台模式时,歌曲停止播放但是当我按下遥控器中的播放按钮时(当我按下双击主页按钮时弹出的菜单),歌曲继续播放它停了下来。

知道为什么我有这个问题吗?

1 个答案:

答案 0 :(得分:1)

请参阅此解决方案:

How do I get my AVPlayer to play while app is in background?

密钥位于info plist中的UIBackgroundModes中。