coding22 coding22 - 7 months ago 41
Swift Question

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

I need to change my code from

AVAudioPlayer
to
AVPlayer
because it supports rewind and
AVAudioPlayer
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.prepareToPlay()
musicPlayer.currentTime = NSTimeInterval(slider.value)
musicPlayer.numberOfLoops = -1
slider.value = Float(musicPlayer.currentTime)

}

Answer

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

self.player.seekToTime(CMTimeMake(Int64(slider.value),1))
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

NSNotificationCenter.defaultCenter().addObserver(self,
selector: "playerItemDidReachEnd:",name: AVPlayerItemDidPlayToEndTimeNotification,
object: self.player.currentItem)

func playerItemDidReachEnd(notification: NSNotification) {
    self.player.seekToTime(kCMTimeZero)
    self.player.play()
}