Swift: AVPlayer release memory / resources
Asked Answered
C

0

6

I am writing an app that need display different video according to the selection of the user. When the user select a video, the function playVideo will be called. And after the video finish playing, then the videoView will be hidden again.

My code is as follows:

var player: AVPlayer?


  func playVideo(String: videoFile) {
    self.videoView.isHidden = false
    let videoURL: NSURL = Bundle.main.url(forResource: videoFile, withExtension: "mp4")! as NSURL
    self.player = AVPlayer(url: videoURL as URL)
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.videoView.frame
    self.videoView.layer.addSublayer(playerLayer)
    let duration : Int64 = 0
    let preferredTimeScale : Int32 = 1
    let seekTime : CMTime = CMTimeMake(duration, preferredTimeScale)
    self.player?.seek(to: seekTime)
    self.player?.play()

    NotificationCenter.default.addObserver(self, selector: #selector(self.playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player?.currentItem)
  }

@objc func playerItemDidReachEnd()
  {
    self.player?.pause()
    self.videoView.isHidden = true
    NotificationCenter.default.removeObserver(self)
  }

However, with the code above, i have several question:

  1. How to delete / deallocate the player gracefully? If just using my current code, will it consume lots of memory?

  2. Every time, when the user press a button, the function playVideo will be called, and the corresponding player will be created and play. Is this the right way to do so? Is there any other method or more efficient way or elegant way to do so?

  3. I did try to replace the code on creation of the player by the following, but it fails to play the video.

    let playerItem: AVPlayerItem = AVPlayerItem(url: videoURL as URL) self.player? = AVPlayer(playerItem: playerItem)

Thank you

Centaur answered 9/2, 2017 at 13:36 Comment(1)
did you happen to get any solution on this?Hunnish

© 2022 - 2024 — McMap. All rights reserved.