简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM