iosswiftaudioavaudioplayer

Play a sound file on repeat in Swift?


I have had success playing sounds by pressing a button, by using the following code. However, I'd like to press a button and have that sound play in a loop/infinitely. How is this achieved? I'd also like to achieve pause/play functionality as well. Thanks in advance.

@IBAction func keyPressed(_ sender: UIButton) {
    playSound(soundName: sender.currentTitle!)
}
        
        
func playSound(soundName: String) { 
    let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
    player = try! AVAudioPlayer(contentsOf: url!)
    player.play()
} 
// End of Play Sound

Solution

  • By default AVAudioPlayer plays its audio from start to finish then stops, but we can control how many times to make it loop by setting its numberOfLoops property. For example, to make your audio play three times in total, you’d write this:

     player.numberOfLoops = 3
    

    if you want the infinite loop then use

     player.numberOfLoops =  -1  
    

    for e.g

      func playSound(soundName: String) { //
            let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
            player = try! AVAudioPlayer(contentsOf: url!)
            player.numberOfLoops =  -1 // set your count here 
            player.play()
    
        } // End of Play Sound