在后台无法正常使用应用时播放音频

时间:2015-06-17 19:37:40

标签: ios background avaudioplayer avaudiosession

我已经搜遍了所有但无法让它始终如一地运作。当应用程序处于后台或锁定屏幕并且振铃器关闭时,我想播放远程推送通知时播放音频。

我跟随的步骤:

1)将所需的背景模式设置为"应用播放音频"进入info.plist。

2)在应用程序中:didFinishLaunchingWithOptions: a)将Audio Session类别设置为Playback b)激活音频会话。 c)让应用程序接收远程控制事件并成为第一响应者

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  // https://developer.apple.com/library/ios/qa/qa1668/_index.html
  // For playback to continue when the screen locks, or when the Ring/Silent switch is set to silent, use the AVAudioSessionCategoryPlayback
  BOOL result = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&sessionError]; // TODO AVAudioSessionCategorySoloAmbient

  if (!result && sessionError) {
    NSLog(@"AppDelegate error setting session category. error %@", sessionError);
  }
  else {
    NSLog(@"AppDelegate setting session category is successful");
  }

  result = [audioSession setActive:YES error:&sessionError];

  if (!result && sessionError) {
    NSLog(@"AppDelegate error activating audio session. error %@", sessionError);
  }
  else {
    NSLog(@"AppDelegate setting session active is successful");
  }

  [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  [self becomeFirstResponder];
}

3)在applicationDidEnterBackground中: a)开始后台任务 b)接收遥控事件

- (void)applicationDidEnterBackground:(UIApplication *)application {
  NSLog(@"AppDelegate applicationDidEnterBackground: called");

  NSLog(@"AppDelegate applicationDidEnterBackground: is calling beginBackgroundTaskWithExpirationHandler:");
  [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];

  NSLog(@"AppDelegate applicationDidEnterBackground: is calling beginReceivingRemoteControlEvents");
  [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

4)当远程通知进入时,播放音频文件

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {

  _currentItem = [AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"Audio" withExtension:@"wav"]];
  _audioPlayer = [AVPlayer playerWithPlayerItem:_currentItem];

  [_currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
  [_audioPlayer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];

  NSLog(@"playAudio: calling [_audioPlayer play] on audioPlayer %@", _audioPlayer);
  [_audioPlayer play];
}

它有时会起作用,但并非总是如此。任何想法如何使这项工作始终如一?

1 个答案:

答案 0 :(得分:0)

我认为你已经在后台开始播放背景音频,即使在applicationDidEnterBackground中开始也为时已晚。你可以做的工作是播放无声音频或暂停音频。您可以使用队列播放器通过循环播放静音音频并在结束时搜索到开头来实现此目的,然后将您想要播放的音频排入队列。