ios – 通过XCode中的AVAudioPlayer开始播放后台任务中的音频

前端之家收集整理的这篇文章主要介绍了ios – 通过XCode中的AVAudioPlayer开始播放后台任务中的音频前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图通过AVAudioPlayer从后台任务开始播放声音然后实例化,所以这就是我所拥有的.

为了便于阅读,我删除了所有用户选择的值.

  1. - (void)restartHandler {
  2. bg = 0;
  3. bg = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
  4. [[UIApplication sharedApplication] endBackgroundTask:bg];
  5. }];
  6. tim = [NSTimer timerWithTimeInterval:.1 target:self selector:@selector(upd) userInfo:nil repeats:YES];
  7. [[NSRunLoop currentRunLoop] addTimer:tim forMode:NSRunLoopCommonModes];
  8. }
  9.  
  10. - (void)upd {
  11. if ([[NSDate date] timeIntervalSinceDate:startDate] >= difference) {
  12. [self playSoundFile];
  13. [tim invalidate];
  14. [[UIApplication sharedApplication] endBackgroundTask:bg];
  15. }
  16. }
  17.  
  18. - (void)playSoundFile {
  19.  
  20. NSError *sessionError = nil;
  21. [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
  22.  
  23.  
  24. // new player object
  25. _player = [[AVQueuePlayer alloc] init];
  26. [_player insertItem:[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"Manamana" withExtension:@"m4a"]] afterItem:nil];
  27.  
  28. [_player setVolume:.7];
  29. [_player play];
  30.  
  31. NSLog(@"Testing");
  32. }

说明:bg,tim,startDate,difference和_player是全局声明的变量.我从用户触发的方法调用 – (void)restartHandler,并在其内部启动一个10Hz的重复计时器 – (void)upd.当达到预设差异时,– (void)调用playSoundFile并启动并启动播放器.调用方法结束时的测试NSLog.

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

任何帮助,提示,解决方案或抬头都非常感谢.

编辑

所以我尝试在运行时使用不同的线程,看起来,如果未在主线程上实例化Player,则会出现同样的问题.
我也试过使用AVPlayer和AVAudioPlayer,其中AVAudioPlayer的.playing属性确实返回YES并且仍然没有播放声音.

解决方法

从我在编写播放器应用程序后学到的内容来看,即使您已将所有内容配置正确,但当您的应用程序已在后台运行超过X秒时,您似乎无法开始播放音频.

要修复它,您必须明智地使用后台任务.
最重要的是你不能在playSoundFile之后立即调用endBackgroundTask.延迟约5-10秒.

以下是我为iOS6和iOS7管理的方法.

1,在plist中添加音频UIBackgroundModes.

2,设置音频会话类别:

3,在主线程中创建AVQueuePlayer,并在应用程序进入后台之前将音频资产排入队列.

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

4,确保AVQueuePlayer中的音频队列永远不会变空,否则您的应用程序将在完成播放最后一个资产时被暂停.

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

猜你在找的iOS相关文章