Search code examples
swiftavaudioplayer

How to add a delay between loops when playing a tone in AVAudioPlayer?


I have created a sample function, which will play a short-duration tone instantly, with the infinite loop. Here is the code:

let audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer.numberOfLoops = -1
audioPlayer.play()

How to create a 5 second delay before the player will play the tone again? Is there a way to do this?


Solution

  • Unfortunately there is no simple way of doing this. You should use AVAudioPlayerDelegate. Please find some example below:

    class ViewController: UIViewController, AVAudioPlayerDelegate
    {
        private var player: AVAudioPlayer!
    
        @objc private func startPlaying()
        {
             self.player = try? AVAudioPlayer(contentsOf: url)
             self.player.delegate = self
             self.player.play()
        }
    
        func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)
        {
             self.perform(#selector(startPlaying), with: nil, afterDelay: 5)
        }
    }
    

    Don't forget to stop selector whenever you want stop the continuation of the audio:

    NSObject.cancelPreviousPerformRequests(withTarget: self)