【问题标题】:Swift: play videos in turns from a for loopSwift:从 for 循环中轮流播放视频
【发布时间】:2017-04-02 00:26:00
【问题描述】:

我正在开发一个应用程序,我需要在其中播放 FOR 循环中的视频,即根据循环的每次迭代中提供的字符串播放本地视频。

问题是当我从循环中调用 playVideo() 函数时,所有视频都会同时播放。我希望他们一个接一个地播放,然后关闭 AVPlayerLayer,即从超级层中删除。 播放单个视频时,playerLayer 被关闭,但如果播放多个视频,则 playerLayer 完好无损。

如何让他们一个接一个地玩?

我读过关于使用调度队列的文章,但对它们了解不多。

代码:

func parseString(string: String){
    var stringArray = string.componentsSeparatedByString(" ")
    logTextView.text = ""
    for i in 0..<stringArray.count{
        playVideo(stringArray[i].lowercaseString)
    }
}

var player: AVPlayer!
var playerLayer: AVPlayerLayer!

// video player

private func playVideo(name: String) {
    guard let path = NSBundle.mainBundle().pathForResource(name, ofType:"mp4") else {
        print("file not found")
        return
    }
    player = AVPlayer(URL: NSURL(fileURLWithPath: path))
    playerLayer = AVPlayerLayer(player: player)
    //        playerController.player = player
    self.playerLayer.frame = self.view.bounds
    self.view!.layer.addSublayer(self.playerLayer)
    self.player!.play()
 //   playing = true

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.playerDidFinishPlaying(_:)),
                                                     name: AVPlayerItemDidPlayToEndTimeNotification, object: player.currentItem)
}

func playerDidFinishPlaying(note: NSNotification) {
    print("Video Finished")
    self.playerLayer.removeFromSuperlayer()
  //  playing = false
}

任何帮助将不胜感激

【问题讨论】:

  • 不要将您的代码作为链接和create a Minimal, Complete, and Verifiable example 在这里指出您的问题。
  • 用代码替换了链接。这个问题可以理解吗?
  • 其实,我不了解 ios,这只是对你的第一篇文章的评论,只是为了让你免于投票:)

标签: ios swift video


【解决方案1】:

那么不要使用 for 循环。取一个int i = 0,然后增加(i++)直到i变得超过stringArray.count

if (i == stringArray.count) { 
    //end 
}

playerDidFinishPlaying(note: NSNotification) 调用执行上述执行的函数。 希望这会有所帮助。

【讨论】:

  • 删除一个图层并添加另一个图层存在延迟。如何无缝过渡?
猜你喜欢
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-20
相关资源
最近更新 更多