Search code examples
swiftavfoundationavaudioplayer

How to Repeat Music in Swift


I would like to know how can I replay my background music forever, right now when the app loads the music begins but when it ends all is quiet, how can I make it to replay all the time.

I am using AVFoundation Framework.

Declaration:

var BackgroundMusic = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("De_Hofnar_Zonnestraal", ofType: "mp3")!), error: nil)

inside viewDidLoad:

BackgroundMusic.play()

Solution

  • Set numberOfLoops property to a negative value.

    backgroundMusic.numberOfLoops = -1
    backgroundMusic.play() // To stop, call stop()