通过XCode中的AVAudioPlayer开始播放后台任务的audio

我试图通过实例化的AVAudioPlayer从后台任务开始播放声音,所以这就是我所得到的。

为了便于阅读,我剪掉了所有用户select的值。

- (void)restartHandler { bg = 0; bg = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ [[UIApplication sharedApplication] endBackgroundTask:bg]; }]; tim = [NSTimer timerWithTimeInterval:.1 target:self selector:@selector(upd) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:tim forMode:NSRunLoopCommonModes]; } - (void)upd { if ([[NSDate date] timeIntervalSinceDate:startDate] >= difference) { [self playSoundFile]; [tim invalidate]; [[UIApplication sharedApplication] endBackgroundTask:bg]; } } - (void)playSoundFile { NSError *sessionError = nil; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError]; // new player object _player = [[AVQueuePlayer alloc] init]; [_player insertItem:[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"Manamana" withExtension:@"m4a"]] afterItem:nil]; [_player setVolume:.7]; [_player play]; NSLog(@"Testing"); } 

说明: bgtimstartDatedifference_player是全局声明的variables。 我从用户触发的方法中调用- (void)restartHandler ,并在里面为- (void)upd启动一个10Hz的重复定时器。 当达到预设的差异时, - (void)playSoundFile被调用并启动并启动播放器。 在方法的末尾testingNSLog被调用。

现在奇怪的是,如果我调用- (void)playSoundFile当应用程序处于活动状态时,一切正常,但是如果从后台任务开始,它将不会播放任何声音。

任何帮助,提示,解决scheme或抬头非常感谢。

编辑

所以我尝试在运行时使用不同的线程,因此,如果播放器没有在主线程上实例化,则会出现同样的问题。 我也尝试使用AVPlayerAVAudioPlayerAVAudioPlayer.playing属性返回YES,仍然没有声音播放。

从编写播放器应用程序后所学到的知识来看,当应用程序已经在后台时间超过X秒时,即使已经正确configuration了所有内容,您也无法开始播放audio。

要解决这个问题,你必须明智地使用后台任务。 最重要的是你不能playSoundFile之后立即调用endBackgroundTask延迟约5-10秒。

这是我如何pipe理iOS6和iOS7的。

1,在plist中添加audioUIBackgroundModes。

2,设置audio会话类别:

3,在主线程中创build一个AVQueuePlayer,并在App进入后台之前排列audio资源

* 用于在后台继续播放(如播放播放列表) *

4,确保AVQueuePlayer中的audio队列不会变空 ,否则在播放最后一个资源时,你的App将被挂起。

5,如果5秒不够你获得下一个资产,你可以使用后台任务来延迟暂停。 资产准备就绪后,您应该在10秒后调用endBackgroundTask

包括你在下面的playSoundFile调用,这应该总是在主线程中运行它

 dispatch_async(dispatch_get_main_queue(), ^{ }); 

如果添加到- (void) playSoundFile来检查玩家是否被创build,如果没有,则创build它

 if(!_player) { _player = [[AVQueuePlayer alloc] init]; } 

在我看来,如果你没有适当的背景模式设置? Xcode截图

另外,看起来像另一个用户有同样的问题,并修复了一个苹果文档的职位。 链接到发布

您可能需要执行以下步骤将audio会话设置为活动状态:

 [audioSession setActive:YES error:&activationError]; 

希望能帮助到你!

如果你需要在后台开始播放声音(没有一个技巧,例如在需要声音之前继续播放音量为零):

  • 在p.list中设置背景模式audio;
  • 将AudioSession类别设置为AVAudioSessionCategoryPlayback
  • 将AudioSession设置为活动状态
  • 当您的后台应用程序运行时,在播放声音之前启动后台任务(显然,当剩余背景时间less于10秒时,声音不会播放)

这现在适用于我。