4

我看到一个注释,这个地址 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];

这个程序有效。但是在后台,声音被切断了。我想继续播放只有背景的声音。我如何将 AVPlayerLayer 与 AVPlayer 分离?

4

1 回答 1

1

您上面的代码没问题,但是在转换到/从后台时做这些事情:

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

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

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

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

干杯。

于 2013-07-26T06:28:18.287 回答