maxpovver maxpovver - 3 months ago 16
iOS Question

Background music problems in iOS

I have problem with this code:

-(void)playSong
{
// ...
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

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];
Comments