使用video(AVPlayer)防止内存泄漏,高内存使用率?

时间:2018-10-11 20:03:16

标签: swift video memory memory-leaks avplayer

我制作了一个应用,其中有一个包含视图和一些按钮的View Controller。在视图上,我显示了一个2秒长的视频,该视频不断重复。

我用仪器检查内存使用情况。它告诉我,在视频所在的View Controller处,我的应用程序的内存使用量持续增加。 30秒后,我的应用程序使用的内存高达1gb。

在代码中,我创建了一个弱变量,该变量打破了保留周期,因此,当我从显示视频的View Controller转到另一个View Controller时,内存使用率就会下降。

但是:我的目的是在每次视频开始重复播放时降低内存使用率,还是我应该考虑做其他事情?

提前谢谢!

backView是我用来显示视频的视图。

//     Set up the video player.

var startVideo = true

private func playVideo(exercise : String, type : String) {

    guard let path = Bundle.main.path(forResource: exercise, ofType: type) else {
        debugPrint("video.mp4 not found")
        return
    }
    weak var player = AVPlayer(url: URL(fileURLWithPath: path))
    let playerController = AVPlayerViewController()
    playerController.player = player
    let playerLayerAV = AVPlayerLayer(player: player)
    //now we set the size of frame to be like the view ("backview")
    playerLayerAV.frame = backView.bounds
    // the backview is the view i'm using it to insert a video
    backView.layer.addSublayer(playerLayerAV)
    player!.play()

    if startVideo == true {
        player!.play()
    }else if startVideo == false {
        player?.pause()
    }

    NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player!.currentItem, queue: .main) { _ in
        player!.seek(to: kCMTimeZero)
        player!.play()
    }

}

1 个答案:

答案 0 :(得分:0)

请尝试以下操作以不断循环播放视频

let playerItem = AVPlayerItem(url: selectedItem)
let player = AVQueuePlayer(playerItem: playerItem)
let playerLooper = AVPlayerLooper(player: player, templateItem: playerItem)
let playerLayer = AVPlayerLayer(player: player)

player.play()