背景中的视频播放

时间:2013-01-24 13:32:39

标签: iphone ios objective-c avplayer avplayerlayer

我看到了这个地址的说明 http://developer.apple.com/library/ios/#qa/qa1668/_index.html

  

注意:如果禁用影片中的视频轨道,或将AVPlayerLayer与其关联的AVPlayer分离,则可以让影片音频继续在后台播放。但是,在应用程序实际切换到后台之前,这些更改必须生效。

   [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
   [self becomeFirstResponder];

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



    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:AnUrl]];
   AVPlayer *avPlayer = [AVPlayer playerWithPlayerItem:playerItem];


   AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
   avPlayerLayer.frame = self.view.layer.bounds;
   UIView *newView = [[UIView alloc] initWithFrame:self.view.bounds];
   [newView.layer addSublayer:avPlayerLayer];
   [self.view addSubview:newView];

   [avPlayer play];

这个程序有效。但在背景中,声音被切断了。我想继续只播放背景声音。我如何从AVPlayer中分离出AVPlayerLayer?

1 个答案:

答案 0 :(得分:1)

上面的代码没问题,但在转换到/来自后台时执行以下操作:

  • 当应用程序变为活动时:(您的avPlayerLayer必须是您添加到视图中的AVPlayerLayer)

    - (void)applicationDidBecomeActive:(UIApplication *)application {
        [avPlayerLayer playerLayerWithPlayer:avPlayer];
    
    }
    
  • 当应用程序进入后台时:(您的avPlayerLayer必须是您添加到视图中的AVPlayerLayer)

    - (void)applicationWillResignActive:(UIApplication *)application {
        [avPlayerLayer playerLayerWithPlayer:nil];
    }
    

另外,不要忘记在plist的UIBackgroundModes中添加音频。

干杯。