首页 文章

AVPlayer不在背景中转发流媒体轨道

提问于
浏览
0

我在后台遇到AVPlayer而不是 playing 的问题 .

这是详细信息:

我有一个AVPlayer对象和一个AVPlayerItem作为我的视图控制器的实例变量,用于从存储在NSMutableArray,linkArray中的链接流式传输音乐 . 当用户在UITableView中点击轨道轨道时,两个对象都实例化如下:

musicPlayerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:[linkArray objectAtIndex:indexPath.row]]];
player = [[AVPlayer alloc] initWithPlayerItem:musicPlayerItem];

......它玩得很完美 . 每当轨道完成时应用程序为 active 它'll skip fine, or when I manually trigger the app to skip track (whether it' s活动或后台运行) . 但是,当应用程序处于后台时(包括设备被锁定时),它会在跳过时播放下一首曲目 .

因此,它会自动跳到下一首曲目,但不会播放 . 我要么必须再次启动应用程序或调用播放(通过耳机控件或系统范围的音乐控件) .

以下是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];
     }

真的希望有人可以帮助我

1 回答

  • 2

    所以问题在于,因为您已启用应用程序在后台播放音频,所以在播放音乐时它将保持活动状态 . 一旦音乐停止,它将被暂停 . 所以你需要时间来在后台执行任务 as soon as the song stops (大多数玩家都有歌曲完成时的回调函数,把这段代码放在开头) . 所以你的代码看起来像这样......

    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

相关问题