2

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:

  1. AudioServicesPlaySystemSound

    The Animation is smooth, but the sound is not played evenly. At least the sound playing doesn't lag the UI whatsoever.

  2. 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?

zs2020
  • 53,766
  • 29
  • 154
  • 219
  • It's AVAudioPlayer. And try searching before asking. This has come up a _lot_ here already. Search for "AVAudioPlayer latency". Your question is a very close duplicate of http://stackoverflow.com/questions/14162805/playing-sound-effect-with-no-latency-in-objective-c for example. – matt May 12 '17 at 04:13
  • 1
    @matt Nope. Non of the posted solution works for my case. – zs2020 May 12 '17 at 04:23

1 Answers1

0

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!

zs2020
  • 53,766
  • 29
  • 154
  • 219