【发布时间】:2013-12-06 10:32:43
【问题描述】:
我正在尝试通过随后实例化的 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");
}
说明:bg、tim、startDate、difference 和 _player 是全局声明的变量。我从用户触发的方法中调用- (void)restartHandler,并在其中启动- (void)upd 的10Hz 重复计时器。当达到预设差异时,- (void)playSoundFile 被调用并启动并启动播放器。方法末尾的测试 NSLog 被调用。
现在奇怪的是,如果我在应用程序处于活动状态时调用 - (void)playSoundFile,一切正常,但如果我从后台任务启动它,它就不会播放任何声音。
编辑
所以我尝试在运行时使用不同的线程,看起来,如果播放器没有在主线程上实例化,则会出现同样的问题。
我还尝试使用AVPlayer 和AVAudioPlayer,其中AVAudioPlayer 的.playing 属性确实返回YES,但仍然没有声音播放。
【问题讨论】:
标签: ios iphone objective-c ios7