maxpovver maxpovver - 1 year ago 96
iOS Question

Background music problems in iOS

I have problem with this code:

// ...
NSLog(@"playing %i", currentSONG);
VKAudio* song = [audios objectAtIndex:currentSONG];
if (player == nil) { // create player object when first called
player = [[AVPlayer alloc] initWithURL:[self urlForVKAudio:song]];
[player play];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; // turn on in background
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAVPlayerItemDidPlayToEndTimeNotification) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
else {
[player replaceCurrentItemWithPlayerItem:
[[AVPlayerItem alloc] initWithURL:[self urlForVKAudio:song]]];
[player play]; // <- this is not working when phone is blocked & screen is off

The problem here is that when I switch into bg mode while playing music it is playing to end of the current item, but the next item isn't playing, so in background mode method

[player play];

doesn't do anything... What am I doing wrong? (bg music mode is on)

Answer Source

As far as I can see you have your AudioSession set up correctly, but don't activate it.

This is what I'm using:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download