Become a MacRumors Supporter for $25/year with no ads, private forums, and more!

iOS Precise timing for audio

counciler

macrumors newbie
Original poster
Jan 8, 2011
25
0
I want to make a custom loop that handles the tick of a timer. The loop will control the timing of when to play the ticks. I'm using the AVAudioPlayer so I can use things like "playAtTime." I can even use the "playerDidFinishPlaying" method for some of the sounds. But I want to overlap some of the sounds, so didFinishPlaying won't work. Essentially, I would like to play a certain set of sounds every 1 or 2 seconds, and precision is necessary.

I'm currently using NSTimer and NSDate for keeping track of the time. But I've noticed sometimes a skip, and skips could screw up the timing of my sounds. So I'm wondering if there's any way to run a loop that is based on time and not frames.
 

dejo

Moderator emeritus
Sep 2, 2004
15,981
450
The Centennial State
Too bad Apple's sample app called Metronome is no longer available. You could've looked at that for a possible solution. Hmm, I may have a backup of that app, although it might be somewhat outdated. I'll let you know if I find it.
 
Comment

ArtOfWarfare

macrumors G3
Nov 26, 2007
9,011
4,885
Too bad Apple's sample app called Metronome is no longer available. You could've looked at that for a possible solution. Hmm, I may have a backup of that app, although it might be somewhat outdated. I'll let you know if I find it.

I would also be interested in this...

all my apps thus far have been silent because whenever I've tested sounds, they always end up out of sync with visual elements.
 
Comment

dejo

Moderator emeritus
Sep 2, 2004
15,981
450
The Centennial State
Found it!

NOTE: This sample code is old, from May 2009. I make no guarantees as to whether it is even usable nowadays.
 

Attachments

  • Metronome.zip
    288 KB · Views: 126
Comment

firewood

macrumors 604
Jul 29, 2003
7,919
1,172
Silicon Valley
Apple's metronome sample app does not keep accurate time.

You have to use mach_time or media time, as all the other timers (such as NSDate) are non-monotonic, and NSTimer timing can be way off as it's firing time depends a lot on what else has been happening in the UI run loop,.

The best method is to use pre-started and continuously running audio queues or the RemoteIO audio unit for producing any sounds that have to be accurately timed or spaced. Or maybe OpenAL.
 
Comment

seepel

macrumors 6502
Dec 22, 2009
471
1
Without knowing more details, I'm not sure if this will help. But when I've had trouble with AVAudioPlayer I moved to AudioQueues. It helped, but my use case was a bit different. What I wanted was to be able to control my loop and jump to different sections of one file at different times. Using AudioQueues gets little convoluted, but it may be worth looking into to see if it suits your needs.
 
Comment
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.