Ajay_Kumar
Ajay_Kumar

Reputation: 1387

AVAudioplayer doesn't play in background

This is NOT duplicate question I had searched every where but unfortunate I hadn't found any solution.

My problem I want to play a music file when app is in background, it should start playing when any local notification is called.

I have a function where I am checking app is exist in background and then I have written statement to play music file but [avaudioplayer play] is always returning NO instead. I have checked error code but it is showing null.

I have also edited info.plist file to set Audio file setting to play in background.

Upvotes: 0

Views: 1686

Answers (1)

Bhupendra
Bhupendra

Reputation: 2545

Set Audio Session Like this: (audioPlayer is the instance of AVPlayer here)

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"inside observer");
    if (self.audioPlayer.status == 1)
    {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                               error:nil];
        [[AVAudioSession sharedInstance] setActive:YES
                                             error:nil];
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [self.audioPlayer play];
    }
}

And one more thing to do Add a field in appname-info.pist of application which is "Required background modes" and add an item to this array named "App plays audio".

It will work for sure then :)

Upvotes: 1

Related Questions