Fin*_*ida 6 iphone objective-c ios ios7
我试图通过AVAudioPlayer从后台任务开始播放声音然后实例化,所以这就是我所拥有的.
为了便于阅读,我删除了所有用户选择的值.
- (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");
}
Run Code Online (Sandbox Code Playgroud)
说明:bg,tim,startDate,difference和_player在全球范围内声明的变量.我- (void)restartHandler从一个用户触发的方法调用,并在其内部启动一个10Hz的重复计时器- (void)upd.当达到预设差异时,- (void)playSoundFile会调用并启动并启动播放器.调用方法结束时的测试NSLog.
现在奇怪的是,如果我- (void)playSoundFile在应用程序处于活动状态时调用,一切正常,但是如果我从后台任务启动它就不会播放任何声音.
任何帮助,提示,解决方案或抬头都非常感谢.
编辑
所以我尝试在运行时使用不同的线程,看起来,如果未在主线程上实例化Player,则会出现同样的问题.我使用也尝试AVPlayer和AVAudioPlayer其中AVAudioPlayer的.playing财产做了回YES还是没声音被打.
Jay*_*hao 12
从我在编写播放器应用程序后学到的内容来看,即使您已将所有内容配置正确,但当您的应用程序已在后台运行超过X秒时,您似乎无法开始播放音频.
要修复它,您必须明智地使用后台任务.最重要的是你不能endBackgroundTask马上打电话playSoundFile.延迟约5-10秒.
以下是我为iOS6和iOS7管理的方法.
1,在plist中添加音频UIBackgroundModes.
2,设置音频会话类别:
3,在主线程中创建AVQueuePlayer,并在应用程序进入后台之前将音频资产排入队列.
*继续在后台播放(如播放播放列表)*
4,确保AVQueuePlayer中的音频队列永远不会变空,否则您的应用程序将在完成播放最后一个资产时被暂停.
5,如果5秒不足以让你获得下一个资产,你可以使用后台任务来延迟暂停.资产准备好后,您应该endBackgroundTask在10秒后打电话.
| 归档时间: |
|
| 查看次数: |
8082 次 |
| 最近记录: |