Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 acheived? I'd also like to acheive pause/play functionality as well. Thanks in advance.

@IBAction func keyPressed(_ sender: UIB`utton) {

            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
like image 286
seanhungerford Avatar asked Nov 25 '19 11:11

seanhungerford


2 Answers

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
like image 168
Anbu.Karthik Avatar answered Nov 13 '22 04:11

Anbu.Karthik


var audioPlayer: AVAudioPlayer?

    func startBackgroundMusic() {
        if let bundle = Bundle.main.path(forResource: "Guru_Nanak_Sahib_Ji", ofType: "mp3") {
            let backgroundMusic = NSURL(fileURLWithPath: bundle)
            do {
                audioPlayer = try AVAudioPlayer(contentsOf:backgroundMusic as URL)
                guard let audioPlayer = audioPlayer else { return }
                audioPlayer.numberOfLoops = -1 // for infinite times
                audioPlayer.prepareToPlay()
                audioPlayer.play()
            } catch {
                print(error)
            }
        }
    }
like image 1
Amanpreet Singh Avatar answered Nov 13 '22 04:11

Amanpreet Singh