我正在尝试在后台播放视频。我确实遵循了很多教程,但没有得到适当的结果。为此,我正在使用 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];
}