user6428350
user6428350

Reputation:

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.

Upvotes: 1

Views: 1488

Answers (4)

Adam
Adam

Reputation: 26927

With SwiftySound, you can do it with a single line of code. All you have to do is pass -1 value for numberOfLoops parameter.

Sound.play(file: "dog", fileExtension: "wav", numberOfLoops: -1)

You can find SwiftySound on GitHub.

Upvotes: 1

nayem
nayem

Reputation: 7605

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()

Upvotes: 4

Lalit kumar
Lalit kumar

Reputation: 2207

For repeat song you can set the Property numberOfLoops to -1 .It will work as infinity loop

player.numberOfLoops = -1

Upvotes: 1

Anil Varghese
Anil Varghese

Reputation: 42977

You need to set the numberOfLoops

player.numberOfLoops = 2 // or whatever 

From Apple doc:

var numberOfLoops: Int

The number of times a sound will return to the beginning, upon reaching the end, to repeat playback.

Upvotes: 1

Related Questions