Search code examples
swiftavaudioplayer

Swift : Replay AVAudioPlayer when song ends


Im trying to get the song to replay when the song ends but it doesn't seem to work. this is how I'm implementing it:

var music1 : AVAudioPlayer! = AVAudioPlayer()


func setUpMusic(){

    let music1Path = NSBundle.mainBundle().pathForResource("Lost", ofType:"mp3")


    let fileURL1 = NSURL(fileURLWithPath: music1Path!)

    do{

        music1 = try AVAudioPlayer(contentsOfURL: fileURL1, fileTypeHint: nil)

    }

    catch{}

    music1.play()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameScene.replayFirstSong(_:)), name: AVPlayerItemDidPlayToEndTimeNotification, object: music1)

}


func replayFirstSong(note: NSNotification){
    print("Inside Replay first song")
    music1.currentTime = 0
    music1.play()
}

Any idea how i can get the song to constantly play in a loop


Solution

  • Try using numberOfLoops:

    Swift:

    var numberOfLoops: Int
    

    OBJECTIVE-C

    @property NSInteger numberOfLoops
    

    Setting it to -1 will loop indefinitely...

    https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioPlayerClassReference/#//apple_ref/occ/instp/AVAudioPlayer/numberOfLoops