我试图在后台播放视频,我确实学了那么多教程,但我没有得到合适的results.For,所以我使用的是AVPlayer.The,我通过这个url可以在应用程序状态为active.But时播放我的视频,我想在后台播放音乐,因为每当我想访问背景中的AVPlayerLayer时,都需要将avPlayerLayer与AVPlayer.But分离开来,它是返回NULL.Please帮助我的。
这是我的代码:
- (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];
}
发布于 2015-02-13 01:22:34
这是一个迟来的答案,但我希望我自己的代码中的一个例子是有帮助的(这段代码位于一个自定义的UIView子类中,我正在显示我的播放器)。
简单地说,我是从我子类中的UIView对象抓取层,然后强制转换到AVPlayerLayer...and,然后它就像使用内置方法一样简单。
- (void)removeLayerFromPlayer
{
AVPlayerLayer *playerLayer = (AVPlayerLayer *)[self layer];
[playerLayer setPlayer:nil];
}
- (void)reattachLayerToPlayer
{
AVPlayerLayer *playerLayer = (AVPlayerLayer *)[self layer];
[playerLayer setPlayer:**your AVPlayer object here**];
}
通常,应该从removeLayerFromPlayer方法中的AppDelegate调用applicationDidEnterBackground方法。使用NSNotificationCenter (我的建议)。
当用户能够再次看到您的应用程序时,应该(可能)使用reattachLayerToPlayer。所以从applicationWillEnterForeground调用这个..。
注意:如果你的应用程序是可见的,当用户双击从主屏幕时,播放机将不会在此时连接到图层,直到用户选择你的应用程序。一个可能的解决办法是在输入背景之前使用播放器的屏幕截图作为占位符。
https://stackoverflow.com/questions/25721021
复制相似问题