8

我已经为我的应用程序正确启用了背景音频(在 plist 中)。在当前播放完成后在后台使用 SPPlaybackManager 播放下一首曲目(当手机被锁定/关闭时)不起作用。

当当前曲目结束并且音频停止时,该应用程序将不会开始播放下一首曲目,直到手机解锁并且我的应用程序再次变为活动状态。

我该如何解决?这是我用来开始播放下一首曲目的代码片段。我观察到当前曲目变为 nil,然后开始播放下一首曲目。日志显示下一个当前曲目正在播放管理器对象中设置,但它是无声的。

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {



    if([keyPath isEqualToString:@"spotifyPlaybackManager.currentTrack"]){

        NSLog(@"%@ %@",keyPath,self.spotifyPlaybackManager.currentTrack);

        if(self.spotifyPlaybackManager.currentTrack==nil && self.mode == PlayerModeSpotify){

            NSLog(@"PLAY NEXT");
            [self.spotifyPlaybackManager playTrack:self.nextSPTrack callback:^(NSError *error){
                if(error) TKLog(@"Spotify Playback Error %@",error);
            }];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:PlayerNowPlayingItemDidChange object:self];
        return;
    }



    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

安慰:

spotifyPlaybackManager.currentTrack (null)
PLAY NEXT
spotifyPlaybackManager.currentTrack <SPTrack: 0x60f8390>: Karaoke
4

2 回答 2

8

解决方案非常简单,但我花了一年时间才意识到这一点。我的旧解决方案是在上一首曲目结束之前启动后台任务,并保持运行直到下一首曲目播放。那很容易出错。反而:

跟踪您的播放状态(播放或暂停)。每当您过渡到 Playing 时,就启动一个后台任务。永远不要停止它,除非你过渡到暂停。即使在曲目之间也保持播放状态。只要您的 info.plist 中有音频背景模式并且正在播放音频,您的后台任务就会无限超时。

一些伪代码:

@interface PlayController
@property BOOL playing;

- (void)playPlaylist:(SPPlaylist*)playlist startingAtRow:(int)row;
@end

@implementation PlayController
- (void)setPlaying:(BOOL)playing
{
    if(playing == _playing) return;
    _playing = playing;

    UIApplication *app = [UIApplication sharedApplication];
    if(playing)
        self.playbackBackgroundTask = [app beginBackgroundTaskWithExpirationHandler:^ {
            NSLog(@"Still playing music but background task expired! :(");
                    [app endBackgroundTask:self.playbackBackgroundTask];
                self.playbackBackgroundTask = UIBackgroundTaskInvalid;
            }];
    else if(!playing && self.playbackBackgroundTask != UIBackgroundTaskInvalid)
        [app endBackgroundTask:self.playbackBackgroundTask];
}
...
@end

编辑:哦,我终于写了博客

于 2012-07-24T14:14:34.330 回答
-2

CocoaLibSpotify 做了大量工作来开始播放曲目,并且可能会在此过程中产生新的内部线程。我怀疑这在背景的音频风格中是允许的,因此您可能需要启动一个临时的后台任务来更改曲目。

于 2012-07-18T07:21:50.943 回答