我遇到的问题是AVPlayer在背景中没有正在播放。
以下是详细信息:
我有一个AVPlayer对象和一个AVPlayerItem作为我的视图控制器的实例变量,用于从存储在NSMutableArray, linkArray 中的链接流式传输音乐。当用户在UITableView中点击轨道轨道时,两个对象都实例化如下:
musicPlayerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:[linkArray objectAtIndex:indexPath.row]]];
player = [[AVPlayer alloc] initWithPlayerItem:musicPlayerItem];
......它完美无缺。当应用程序活动时,只要轨道完成,它就会跳过很好,或者当我手动触发应用程序跳过轨道时(无论是活动还是背景)。但是,当应用程序处于后台时(包括设备被锁定时),它会在跳过时播放下一首曲目。
因此,它会自动跳到下一首曲目,但不会播放。我要么必须让应用程序再次激活,要么调用播放(通过耳机控件或系统范围的音乐控件)。
以下是skipTrack方法的代码,该方法在手动调用时或在歌曲到达轨道末尾时由系统调用:
if (nowPlaying == [linkArray count]-1) {
nowPlaying = 0;
musicPlayerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:[linkArray objectAtIndex:0]]];
player = [[AVPlayer alloc] initWithPlayerItem:musicPlayerItem];
} else {
NSLog(@"NowPlaying (before increment: %i", nowPlaying);
//If not, increment nowPlaying by one and play
nowPlaying++;
NSLog(@"NowPlaying (after increment: %i", nowPlaying);
musicPlayerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:[linkArray objectAtIndex:nowPlaying]]];
player = [[AVPlayer alloc] initWithPlayerItem:musicPlayerItem];
}
真的希望有人可以帮助我
答案 0 :(得分:2)
所以问题在于,因为您已启用应用在后台播放音频,所以在播放音乐时它会保持活动状态。一旦音乐停止,它将被暂停。因此,一旦歌曲停止,你需要时间在后台执行任务 (大多数玩家在歌曲完成时都有回调函数,将此代码放在开头)。所以你的代码看起来像这样......
UIBackgroundTaskIdentifier newTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
// Clean up any unfinished task business by marking where you.
// stopped or ending the task outright.
[application endBackgroundTask:newTaskID];
newTaskID = UIBackgroundTaskInvalid;
}];];
if (nowPlaying == [linkArray count]-1) {
nowPlaying = 0;
musicPlayerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:[linkArray objectAtIndex:0]]];
player = [[AVPlayer alloc] initWithPlayerItem:musicPlayerItem];
} else {
NSLog(@"NowPlaying (before increment: %i", nowPlaying);
//If not, increment nowPlaying by one and play
nowPlaying++;
NSLog(@"NowPlaying (after increment: %i", nowPlaying);
musicPlayerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:[linkArray objectAtIndex:nowPlaying]]];
player = [[AVPlayer alloc] initWithPlayerItem:musicPlayerItem];
}
[[UIApplication sharedApplication] endBackgroundTask:newTaskID];
newTaskID = UIBackgroundTaskInvalid;'
“beginBackgroundTaskWithExpirationHandler:”方法将为您提供一些时间在后台执行操作。如果您的时间用完,则会执行发送到该方法的代码块。你需要包含那些出错的东西,你需要清理任务。在开发库中了解更多相关信息:here