Search code examples
swiftavplayer

Play audio again after finished with AVPlayer swift


How to play again the same audio after finished? Now I use this code with AVPlayer:

fileprivate func play () {
    guard let url = URL(string: record.recordUrl) else { return }
    let playItem = AVPlayerItem(url: url)
    player.replaceCurrentItem(with: playItem)
    NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playItem)
    player.play()
}

@objc func playerDidFinishPlaying(note: NSNotification) {
    print("Player finished")
    currentTimeSlider.setValue(0, animated: true)
    currentTimeLabel.text = "00:00"
}

Solution

  • @objc func playerDidFinishPlaying(note: NSNotification) {
        print("Player finished")
        currentTimeSlider.setValue(0, animated: true)
        currentTimeLabel.text = "00:00"
    
        //Swift 4
        player.seek(to: .zero, toleranceBefore: .zero, toleranceAfter: .zero)
    
        //Swift 2 & 3 (I believe for 2 & 3)
        //player.seek(to: kCMTimeZero, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)
    
        //Play
        player.play()
    }
    

    I added the seek back to the beginning (the tolerance makes sure it is exactly at zero, and not around zero with some margin of error).

    Also added the feature to play when done.