1

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Maybe you should set category first. – Lumialxk Aug 28 '17 at 06:27
  • I think you have to throw notification when song complete and play it again when using AVPlayer. If you want to use MVMoviePlayer than `moviePlayerController.repeatMode = MPMovieRepeatModeOne;` `//MPMovieRepeatModeOne <= use for infinite loop` – Kumar Aug 28 '17 at 06:30
  • Possible duplicate of [How to Repeat Music in Swift](https://stackoverflow.com/questions/28911810/how-to-repeat-music-in-swift) – nayem Aug 28 '17 at 06:34
  • [Answer](https://stackoverflow.com/a/11177333/3687801) with better explanation – nayem Aug 28 '17 at 06:39

4 Answers4

4

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()
nayem
  • 7,285
  • 1
  • 33
  • 51
1

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.

Anil Varghese
  • 42,757
  • 9
  • 93
  • 110
1

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

player.numberOfLoops = -1
Lalit kumar
  • 1,797
  • 1
  • 8
  • 14
1

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.

Adam
  • 26,549
  • 8
  • 62
  • 79