coding22 coding22 - 1 year ago 94
Swift Question

How would I convert these four lines of code from AVAudioPlayer to AVPlayer?

I need to change my code from

because it supports rewind and
doesn't. Im having trouble with these four lines of code that seeks the audio thats playing using a slider. Here is the code I have:

func changeAudioTime() {

//musicPlayer is declared as AVAudioPlayer and I want to change it to AVPlayer and I named the variable player

musicPlayer.currentTime = NSTimeInterval(slider.value)
musicPlayer.numberOfLoops = -1
slider.value = Float(musicPlayer.currentTime)


Answer Source

For setting the time in both the case you can use this:

slider.value = Float(CMTimeGetSeconds(self.player.currentTime()))

For looping you may try like this, as there is no direct method of loop, till you want to repeat you may set flag/observer and repeat the song if repeat is off you can don't execute observer/seek

selector: "playerItemDidReachEnd:",name: AVPlayerItemDidPlayToEndTimeNotification,
object: self.player.currentItem)

func playerItemDidReachEnd(notification: NSNotification) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download