为了便于阅读,我删除了所有用户选择的值.
- (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"); }
说明:bg,tim,startDate,difference和_player是全局声明的变量.我从用户触发的方法调用 – (void)restartHandler,并在其内部启动一个10Hz的重复计时器 – (void)upd.当达到预设差异时,– (void)调用playSoundFile并启动并启动播放器.调用方法结束时的测试NSLog.
现在奇怪的是,如果我在应用程序处于活动状态时调用 – (void)playSoundFile,一切正常,但是如果我从后台任务启动它就不会播放任何声音.
任何帮助,提示,解决方案或抬头都非常感谢.
编辑
所以我尝试在运行时使用不同的线程,看起来,如果未在主线程上实例化Player,则会出现同样的问题.
我也试过使用AVPlayer和AVAudioPlayer,其中AVAudioPlayer的.playing属性确实返回YES并且仍然没有播放声音.
解决方法
要修复它,您必须明智地使用后台任务.
最重要的是你不能在playSoundFile之后立即调用endBackgroundTask.延迟约5-10秒.
以下是我为iOS6和iOS7管理的方法.
1,在plist中添加音频UIBackgroundModes.
2,设置音频会话类别:
3,在主线程中创建AVQueuePlayer,并在应用程序进入后台之前将音频资产排入队列.
*继续在后台播放(如播放播放列表)*
4,确保AVQueuePlayer中的音频队列永远不会变空,否则您的应用程序将在完成播放最后一个资产时被暂停.
5,如果5秒不足以让你获得下一个资产,你可以使用后台任务来延迟暂停.资产准备就绪后,您应该在10秒后调用endBackgroundTask.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。