Audio playing while app in background iOS

前端 未结 7 901
我寻月下人不归
我寻月下人不归 2021-02-05 17:19

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

相关标签:
7条回答
  • 2021-02-05 18:15

    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

    0 讨论(0)
提交回复
热议问题