我正在尝试非常精确地定时发出声音。
我使用这段代码来创建计时器:
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1ull*500000000, 5000ull);
dispatch_source_set_event_handler(timer, ^{[myAVAudioPlayer play];});
dispatch_resume(timer);
myAVAudioPlayer 是这样初始化的:
NSURL *soundURL = [NSURL fileURLWithPath:[mainBundle pathForResource:@"clock" ofType:@"aiff"]];
myAVAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
[myAVAudioPlayer prepareToPlay];
我还尝试使用 .caf 格式的声音和来自 BubbleLevel 示例代码的 Apple 的 SoundEffect 类,并且在性能上没有显着差异。
如果射速低,声音就相当准确。但如果我加快发射速度,声音就会非常不准确。
如有任何帮助,我们将不胜感激。
最佳答案
调度计时器不是为音频精度而设计的。 IIRC 是您希望精确控制时间的情况,Apple 建议人们仍然直接使用线程而不是调度队列的少数几个领域之一。
比这更好的是调查 Core Audio ,除其他外,旨在准确处理您想要的:精确控制时间。我帮不上太多细节,因为我不熟悉 API,而且它的文档记录很糟糕,但是一个快速的谷歌出现了 at least one person doing the same thing ,所以您可能会幸运地找到更好的解决方案。
关于objective-c - 带音频的计时器精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6701121/