Search code examples
iosxcodeavaudioplayerrepeat

How can I repeat a song in iOS?


I am trying to repeat a song in my app. However, it just plays it until the end, then it stops altogether. How can I put in a loop feature for this?

This is my code in my viewDidLoad:

    do
    {
        let audioPath = Bundle.main.path(forResource: "APP4", ofType: "mp3")
        try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)

    }

    catch

    {

        //catch error
    }

    let session = AVAudioSession.sharedInstance()

    do
    {

        try session.setCategory(AVAudioSessionCategoryPlayback)

    }

    catch
    {

    }
          player.play()

I'm using Xcode 8.


Solution

  • Use AVAudioPlayer's numberOfLoops property for getting the repeat feature.

    From the Apple doc's Discussion section:

    A value of 0, which is the default, means to play the sound once. Set a positive integer value to specify the number of times to return to the start and play again. For example, specifying a value of 1 results in a total of two plays of the sound. Set any negative integer value to loop the sound indefinitely until you call the stop() method.

    So use:

    player.numberOfLoops = n - 1 // here n (positive integer) denotes how many times you want to play the sound
    

    Or, to avail the infinite loop use:

    player.numberOfLoops = -1
    // But somewhere in your code, you need to stop this
    

    To stop the playing:

    player.stop()