0

我正在尝试在后台播放视频。我确实遵循了很多教程,但没有得到适当的结果。为此,我正在使用 AVPlayer。我遵循这个 url,只要应用程序状态处于活动状态,我就可以通过它播放我的视频。但是我想在后台播放音乐,因为我需要从 AVPlayer 中分离 AVPlayerLayer。但是每当我想在后台访问 avPlayerLayer 时,它都会返回 NULL。请帮助我。

这是我的代码:

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

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

NSURL *url = [[NSBundle mainBundle] URLForResource:@"sample"

                                     withExtension:@"m4v"

                                      subdirectory:nil];
avPlayerItem = [AVPlayerItem playerItemWithURL:url];
self.songPlayer = [AVPlayer playerWithPlayerItem:avPlayerItem];


self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer: self.songPlayer];

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

[ self.songPlayer play];


// Do any additional setup after loading the view, typically from a nib.
}

iewController *vc=[[ViewController alloc]init];
NSLog(@"%@",vc.avPlayerLayer);
 vc.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:nil];
 }



- (void)applicationDidBecomeActive:(UIApplication *)application
 {
  ViewController *vc=[[ViewController alloc]init];
  vc.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:vc.songPlayer];
 }
4

1 回答 1

0

这是一个较晚的答案,但我希望我自己的代码中的一个示例会有所帮助(此代码位于自定义 UIView 子类中;我在其中显示我的播放器的视图)。

简而言之:我从 UIView 对象中获取层,然后我强制转换为 AVPlayerLayer ......然后从那里它就像使用内置方法一样简单。

- (void)removeLayerFromPlayer
{
    AVPlayerLayer *playerLayer = (AVPlayerLayer *)[self layer];
    [playerLayer setPlayer:nil];
}

- (void)reattachLayerToPlayer
{
    AVPlayerLayer *playerLayer = (AVPlayerLayer *)[self layer];
    [playerLayer setPlayer:**your AVPlayer object here**];
}

通常应该从 applicationDidEnterBackground 方法中的 AppDelegate 调用 removeLayerFromPlayer 方法。使用 NSNotificationCenter (我的建议)。

当用户可以再次看到您的应用时,应该(可能)使用 reattachLayerToPlayer。所以从 applicationWillEnterForeground 调用它...

注意:如果当用户从主屏幕双击时您的应用程序可见,则此时播放器不会附加到图层,直到用户选择您的应用程序。一种可能的解决方法是在进入背景之前使用播放器的屏幕截图作为占位符。

于 2015-02-13T01:22:34.607 回答