Search code examples
iosswiftavplayercmtimeseektotime

avplayer finishing song on seekToTime


I'm trying to have avPlayer restart the current song when the skip back button is selected if it's after about 5 seconds into the song, and jump to times according to where the slider is moved to. Here's my code for these functions:

@IBAction func buttonBackTouchDown(sender: AnyObject) {
    if (Float(CMTimeGetSeconds((avPlayerItem?.currentTime())!)) > 5) {
        //restartSong = true
        avPlayer.currentItem!.seekToTime(kCMTimeZero)
        //self.loadSongValues()
        //restartSongTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("setRestartSongToFalse"), userInfo: nil, repeats: false)
    }
    else if (Float(CMTimeGetSeconds((avPlayerItem?.currentTime())!)) < 5) {
        self.previousSong()
    }
}


@IBAction func sliderTouchDown(sender: AnyObject) {
        self.sliderTimer.invalidate()
        avPlayer.pause()
        self.overlayOn()
    }


@IBAction func sliderTouchUpInside(sender: AnyObject) {
        //restartSongTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("setRestartSongToFalse"), userInfo: nil, repeats: false)
        //NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("startSliderTimer"), userInfo: nil, repeats: false)
        self.startLabelTimer()
        avPlayer.play()
        self.updateNowPlayingInfoCenter()
        self.overlayOff()
    }

The problem I'm having is that if the song is over 1 minute in, or it's almost finished and I move the slider too far back, it SOMETIMES triggers this observer:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "skipSong", name: AVPlayerItemDidPlayToEndTimeNotification, object: avPlayerItem)

I tried looking in Apple's references and looked to other questions here on StackOverflow, but couldn't find anything.

Maybe I'm not understanding how to properly use CMTime, or something is weird with the files, but this is really weird to me.

Any help is appreciated. Thanks in advance!


Solution

  • I'm experiencing also a lot of Issues with the AVPlayer and particularly the SeekToTime method.

    When you do

    avPlayer.currentItem!.seekToTime(kCMTimeZero)
    

    avPlayer is Jumping to the 0 Frame and not the First frame as it should. the Frame #0 and the last frame seem to be the Same for the AVPlayer. Try the Following: (like jumping to time 0.001 instead of 0)

            let seekTime : CMTime = CMTimeMake(1, 1000)
            avPlayer!.seekToTime(seekTime)