开发者

Timer precision with audio

I am trying to make a very precisely timed firing of a sound.

I used this code to create the timer:

    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];});
    d开发者_Python百科ispatch_resume(timer);

myAVAudioPlayer is initialized like this:

    NSURL *soundURL = [NSURL fileURLWithPath:[mainBundle pathForResource:@"clock" ofType:@"aiff"]];
    myAVAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
    [myAVAudioPlayer prepareToPlay];

I have also tried to use .caf format of the sound and Apple's SoundEffect class from BubbleLevel example code and there is no notable difference in performance.

If the firing rate is low the sound is quite accurate. But if I pace up the firing rate the sound is very inaccurate.

Any help would be greatly appreciated.


Dispatch timers aren't designed for audio-precision accuracy. Cases where you want precise control over timing are, IIRC, one of the few areas where Apple recommend that people still use threads directly instead of dispatch queues.

Better than that would be to investigate Core Audio, which amongst other things, is designed to handle exactly what you want: precise control over timing. I can't help in much detail there, as I'm not familiar with the API and it's legendarily badly documented, however a quick google turned up at least one person doing the same thing, so you may have luck finding a better solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜