简体   繁体   中英

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];});
    dispatch_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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM