So here is the story.
I have a timer and timer.setEventHandler
renders animation (something like adding 10 circles in the UI every 125ms) when I tap a button. The animation runs smoothly and so far so good.
Now I want to add sound (the sound plays 10mm like a beep but from a mp3 file) every time when the circle is added. I tried 2 approaches:
AudioServicesPlaySystemSound
The Animation is smooth, but the sound is not played evenly. At least the sound playing doesn't lag the UI whatsoever.
Use AVAudioPlay
I prepared the AVAudioPlay instance in a singleton class and every time the animation logic calls play()
in a DispatchedQueue to make sure the sound is played in a separate thread. The first time when the button is pressed, the animation is lagged. However, when I press the button again shortly (within 2 seconds) when the animation is done, the animation and sound will be played perfectly. However, if I wait for longer time like 10 seconds since the last sound was played, the animation will be lagged and sound is kind of bursting out.
I am wondering if iOS (I am running iOS 10 on iPad Air 2) actually put AVAudioPlay instances on sleep when it is not active. Unless I press the button within the short time (2 seconds) since the last sound was played, the AVAudioPlay thread will be active all the time.
Any idea?
I figured it out.
Use a timer to play sound at 0 volumn every 1 second forever to keep the audio session alive. It sounds stupid but it works like a charm!