Audio playing while app in background iOS

I have an app mostly based around Core Bluetooth.
When something specific happens, the app is woken up using Core Bluetooth background modes and it fires off an alarm, however I can’t get the alarm working when the app is not in the foreground.

I have an Alarm Singleton class which initialises AVAudioPlayer like this:

  • Playing sounds in iPhone SDK?
  • swift xcode play sound files from player list
  • Playing a sound with AVAudioPlayer
  • Saving a recorded AVAudioRecorder sound file: Now what? ( iOS, Xcode 4 )
  • How to reverse an audio file?
  • Are there any other iOS system sounds available other than 'tock'?
  • NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                        pathForResource:soundName
                                 ofType:@"caf"]];
    
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    [self.player prepareToPlay];
    self.player.numberOfLoops = -1;
    [self.player setVolume:1.0];
    
    NSLog(@"%@", self.player);
    

    This is the method that is called when my alarm code is called:

    -(void)startAlert
    {
        NSLog(@"%s", __FUNCTION__);
    
        playing = YES;
        [self.player play];
        NSLog(@"%i", self.player.playing);
    
        if (vibrate) {
            [self vibratePattern];
        }
    }
    

    Now when the app is in the foreground, self.player.playing returns 1 however when the app is in the background self.player.playing returns 0. Why would this be?
    All the code is being called, so the app is awake and functioning.
    The vibrate works perfectly which uses AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

    Any idea why this sound won’t play?

    Thanks

    6 Solutions Collect From Internet About “Audio playing while app in background iOS”

    I have an App than also needs background audio but my App works with the App background mode “Voice over IP” as it needs to record sometimes. I play background audio telling the App singleton I need to play audio in background:

    UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
    if([thePlayer play]){
        newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];   
    }
    

    EDIT: You must call [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL]; before your app goes to background. In my app, it is at the same time you start playing, in yours, if the player might be started in background, you should do:

    - (void)applicationDidEnterBackground:(UIApplication *)application{
      // You should retain newTaskId to check for background tasks and finish them 
      newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];   
    }
    

    Apple has a nice Technical Q&A article about this in its documentation (see also Playing and Recording Background Audio).

    I think one big thing missing is that you haven’t activated the Audio Background Mode in the Xcode settings:
    enter image description here

    Maybe also adding [self.player prepareToPlay] in your alert method is helpful.

    I take it you have the audio background mode specified for the app. Even so, I’m not sure you can set an audio session to be active while in the background. You need to have activated it before going into the background. You may also need to play some silent audio to keep this active, but this is seems like bad practice (it may drain the battery). Looking at the docs for notifications there seems to be a way to have a local notification play an audio sample that’s included in your bundle, which seems to be what you want to do, so maybe that’s the way to go.

    Apple docs

    Either enable audio support from the Background modes section of the Capabilities tab

    Or enable this support by including the UIBackgroundModes key with the audio value in your app’s Info.plist file

    Try this :

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
    

    link

    Try this http://www.sagorin.org/ios-playing-audio-in-background-audio/

    You need to enable your app to handle audiosession interruptions (and ended interruptions) while in the background. Apps handle audio interruptions through notification center:

    1. First, register your app with the notification center:

      - (void) registerForMediaPlayerNotifications {
      
          [notificationCenter addObserver : self
                                  selector: @selector (handle_iPodLibraryChanged:)
                                      name: MPMediaLibraryDidChangeNotification
                                    object: musicPlayer];
      
          [[MPMediaLibrary defaultMediaLibrary] beginGeneratingLibraryChangeNotifications];
      
      }
      
    2. Now save player state when interruption begins:

      - (void) audioPlayerBeginInterruption: player {
      
          NSLog (@"Interrupted. The system has paused audio playback.");
      
          if (playing) {
              playing = NO;
              interruptedOnPlayback = YES;
          }
      }
      
    3. And reactivate audio session and resume playback when interruption ends:

      -(void) audioPlayerEndInterruption: player {
      
          NSLog (@"Interruption ended. Resuming audio playback.");
      
          [[AVAudioSession sharedInstance] setActive: YES error: nil];
      
          if (interruptedOnPlayback) {
              [appSoundPlayer prepareToPlay];
              [appSoundPlayer play];
              playing = YES;
              interruptedOnPlayback = NO;
          }
      }
      

    Here’s Apple’s sample code with full implementation of what you’re trying to achieve:

    https://developer.apple.com/library/ios/samplecode/AddMusic/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008845