【问题标题】:Stop AVPlayer from playing in tableviewcell停止 AVPlayer 在 tableviewcell 中播放
【发布时间】:2017-08-03 09:50:06
【问题描述】:

我使用AVPlayer 在我的TableViewCell 中显示视频。它正在 TableViewCell 播放,但问题是我无法阻止它。 我已经使用此代码在 cellforRow 中播放视频

        avPlayer = AVPlayer(url: videoURL! as URL)
        playerLayer = AVPlayerLayer(player: avPlayer)
        playerLayer.frame = CGRect(x: cell.videoview.frame.origin.x, y: cell.videoview.frame.origin.x, width:cell.videoview.frame.size.width, height: cell.videoview.frame.size.height)
        cell.videoview.layer.addSublayer(playerLayer)
        avPlayer?.play()

avPlayer 和 playerLayer 在 viewController 中定义如下

var avPlayer  : AVPlayer?
var playerLayer = AVPlayerLayer()

我正在使用此代码来停止视频

    self.avPlayer?.pause()
    self.playerLayer.removeFromSuperlayer()
    self.avPlayer?.rate = 0.0
    self.avPlayer?.replaceCurrentItem(with: nil)
    self.avPlayer = nil

我的问题是,如何停止在AVPlayerLayer 上通过AVPlayer 运行的视频? 请提出解决方案,如果有任何替代方案,也请提出建议。

【问题讨论】:

  • 检查 HomeViewController 中不存在名为 stopVideoPlayer 的 ibaction。签入故事板并删除不良连接。
  • 它存在我已经创建了一个断点来检查它在这条线上崩溃 self.avPlayer = nil
  • 你实现了这个方法stopVideoPlayer

标签: ios swift uitableview avplayer


【解决方案1】:

由于单元格的可重用行为,它会自行释放子视图实例,因此您必须在 didEndDisplayingCell 委托方法中停止它。

override func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    if let cell = cell as? MyCustomCell {
        if let play = player {
           print("stopped")
           play.pause()
           player = nil
           print("player deallocated")
        } else {
           print("player was already deallocated")
        }
    }
}

或

您可以获取单元格实例并搜索播放器实例并停止它。

for view in cell.subviews {
      //after comparison stop the player here
}

【讨论】:

  • 我认为链接到方法文档会更好;)
  • @Salman_Ghumsani 我需要知道如何停止正在播放的视频?你知道如何在播放时停止 avplayer。
  • 这与我在上面所做的代码相同,但我仍然无法在播放时停止 avplayer
  • 您在didEndDisplayingCell 中使用 if let 检查?
  • 还请指定打印哪个语句?
【解决方案2】:

AVPlayer 没有停止方法。因此,您可以将搜索时间设置为 0 并暂停播放器。

videoPlayer.seek(to: CMTimeMake(0, 1))
videoPlayer.pause()

此外,如果您想检查 videoCell 是否可见。您可以使用下面的代码,它将为您提供可见的单元格索引数组。因此,您可以简单地检查数组是否包含您的视频单元格索引。

tableView.indexPathsForVisibleRows

【讨论】:

  • 此代码仍然无法阻止播放器。此外,即使播放器在屏幕上,我也需要停止播放器。问题是代码无法阻止播放器。
  • 你必须像这个 playerLayer 一样使用这个代码 sn-p。 videoPlayer.pause() 。因为您在 playerLayer 之上添加了 videoPlayer。它可能会起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 2013-10-17
  • 2017-02-26
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多