2017-06-13 57 views
0

我有一个AVPlayer,我想暂停并在点击时继续。暂停/播放AVPlayer的问题

我决定去做这件事的方法是在AVPlayer所附的视图上使用tapGestureRecognizer。

当有一个水龙头布尔变量didSelect变为真时。当第二次敲击时,didSelect变为假。

有趣的是,当我在AVPlayerItemDidPlayToEndTime通知使用

if didSelect == false { 
     player.play() 
    } 

    if didSelect == true { 
     player.pause() 
    } 

,它工作正常,但只有后的视频完整。这让我想知道是否有沿AVPlayerItemIsIsPlaying的行通知,但我还没有找到任何东西。

下面是代码的样子。

playerView.layer.cornerRadius = playerView.bounds.width * 0.025 

    guard let path = Bundle.main.path(forResource: "video", ofType:"mp4") else { 
     debugPrint("video.m4v not found") 
     return 
    } 

    let player = AVPlayer(url: URL(fileURLWithPath: path)) 

    let playerLayer = AVPlayerLayer(player: player) 
    playerLayer.frame = playerView.frame 
    playerLayer.frame = self.frame 

    playerLayer.frame = playerView.bounds 
    playerLayer.masksToBounds = true 
    playerLayer.cornerRadius = playerView.bounds.width * 0.025 

    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill 


    self.playerView.layer.addSublayer(playerLayer) 

     player.isMuted = true 
     player.play() 




    if didSelect == false { 
     player.play() 
    } 

    if didSelect == true { 
     player.pause() 
    } 

    //looper 
    NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem, queue: nil) 
    { notification in 
     let t1 = CMTimeMake(5, 100) 
     player.seek(to: t1) 

     player.play() 
    } 

回答

0

我创建了一个全球参考玩家

var player: AVPlayer?

,并引用了在UITapGestureRecognizer功能,现在控制暂停/从那里玩。

0

我遇到了同样的问题,最终创建了一个将playblack控件嵌入到视频中的AVPLayerViewController。

这是修改过的代码,我希望它有帮助。

import AVKit 
import AVFoundation 

let avController = AVPlayerViewController() 
avController.showsPlaybackControls = true 

let player = AVPlayer(url: URL(fileURLWithPath: path)) 

let playerLayer = AVPlayerLayer(player: player) 
playerLayer.frame = playerView.frame 


playerLayer.frame = playerView.bounds 
playerLayer.masksToBounds = true 
playerLayer.cornerRadius = playerView.bounds.width * 0.025 

playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill 

avController.player = playerLayer 

avController.view.frame = playerView.bounds 

self.playerView.addSubview(avController.view)