0

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.

Ajay_Kumar
  • 1,381
  • 10
  • 34
  • 62
  • refer http://stackoverflow.com/questions/7965419/avaudioplayer-play-file-in-background and http://stackoverflow.com/questions/7619794/play-music-in-the-background-using-avaudioplayer – Cris Jan 25 '13 at 13:15
  • These 2 above I had already referred but no result :(. PLAY function is returning NO. My app is in background and then I am trying to play music (not like startMusic--->Go in Background--->keep playing) – Ajay_Kumar Jan 25 '13 at 13:28
  • i guess it needs to run on main thread and then you can put in background thread and not other way round,not sure though! – Cris Jan 25 '13 at 13:31
  • 1
    @Cris I also executed in mainthread but unfortunate same... – Ajay_Kumar Jan 25 '13 at 13:50
  • See my answer and are you using a device or simulator. – iProgrammed Jan 25 '13 at 14:57

1 Answers1

1

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 :)

Bhupendra
  • 2,525
  • 18
  • 20