I have a 30 second audio file and I would like to get callbacks at 12 different points during playback so I can start some animations. For example, at 1.3, 3.2, 4.8, 9.8, 12.3, 15.5, 18.1, 20.4, 22.5, 24.5, 27, and 29 seconds. How would I do this on iOS?
Share
There are many, many ways to do this in iOS/Objective-C. I’m assuming you don’t want a callback from the actual audio player guaranteeing the audio has been played. The mechanism you’re using to play the audio may have a callback for when the audio actually starts playing though (to help you sync things better).
A very common one is
or you can lookup
NSTimerto see how to use that,or the new fangled Grand Central Dispatch version
If your using newer OS and multi-core devices, GCD is a good way to go.
If you’re using an animation package (cocos2d, for example), they often have timing hooks as well.
Added for expanded question:
If all the animations are different, then that’s the amount of work you have to do. If they’re all the same (or some are the same), you can have an NSTimer call you every .1 (for example) seconds, then test the actual amount of time passed, when you hit the next threshold you trigger the action. (Things aren’t guaranteed to run on time – if your app is a CPU hog it could be running late.)
Yes, if it’s going to get more complicated, you likely want to build some classes to handle it. Build an array in time order and treat it like a queue.