Background Audio with cocoalibspotify

蓝咒 提交于 2019-12-03 03:54:07

The solution is very simple but it took me a year to realize it. My old solution was to start a background task just before the previous track ended, and keep it running until the next track was playing. That was very error prone. Instead:

Keep track of your playing state (playing or paused). Whenever you transition into Playing, start a background task. Never stop it, unless you transition into Paused. Keep the state as Playing even between tracks. As long as you have the audio background mode in your info.plist and audio is playing, your background task will have an infinite timeout.

Some pseudo code:

@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

Edit: Oh, and I finally blogged about it.

CocoaLibSpotify does a lot of work to start playing a track and will likely spawn new internal threads in the process. I doubt this is allowed in the audio style of backgrounding so you'll likely need to start a temporary background task to change tracks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!