如何从AVPlayer中分离AVPlayerLayer?

时间:2014-09-08 09:25:45

标签: objective-c ios7 avplayer avplayerlayer

我正在尝试在后台播放视频。我确实关注了很多教程,但我没有得到合适的结果。为此我使用的是AVPlayer。我按照这个网址通过它我可以在应用程序状态下播放我的视频我想在后台播放音乐,因为我需要从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];
 }

1 个答案:

答案 0 :(得分: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 ...

调用它

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