简体   繁体   中英

iOS 7: Audio not playing in background

I'm writing an iPhone app that plays sound at regular intervals via a timer. The first version of this app played audio just fine when it was minimized, or when the screen went blank, however, after adding some UI, it looks like this has stopped. I'm not sure why, or even how to diagnose this (removing the UI code doesn't solve the issue).

I've set the background mode in the info.plist file: ("App plays audio or streams audio/video via Airplay") and I've also got the following in my app delegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // Override point for customization after application launch.
  NSError *setCategoryErr = nil;
  NSError *activationErr  = nil;

  [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback 
                                     error:&setCategoryErr];

  [[AVAudioSession sharedInstance] setActive:YES 
                                   error:&activationErr];  
  return YES;  
}

And in my ViewDidLayoutSubViews method, I initialize AVPLayer thusly:

  self.fAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
  self.fAudioPlayer.numberOfLoops = 0;
  [self.fAudioPlayer setVolume:volume];
  [self.fVolumeLevelSlider setValue:volume];  

Where fAudioPlayer is of type AVAudioPlayer. When my timer is hit, I play the audio like this:

  self.fBGTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
  [self.fAudioPlayer play];

I'm still going through my changes to see what, if anything, I had put in that could cause the sound to stop playing in the background from one app version to the next. Does anyone see anything here that could be amiss?

Moving these lines:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];

Right before I start playing in my timer, resolved the issue.

In order to keep the player to keep playing even when the app is in background, you have to update the application's info.plist file by adding the following key

"Required background modes" and add the value to "App plays audio or streams audio/video using AirPlay"

Setting this property allows the app to even play/stream Audio in background, while app is minimized or another app is open (including screen saver).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM