ios - lite - swift play video




隱藏AVPlayerViewController中的控件-僅在開始時 (3)

如果將AVPlayerViewController.showsPlaybackControls設置為false,則控件將根本不顯示。 即使你點擊屏幕。

我希望控件開始隱藏,但仍然能夠通過點擊來召喚它們。 如果我將提到的屬性設置為true,它們就會開始顯示。 (是的,他們在幾秒鐘後褪色。)有沒有辦法開始隱藏,但仍然可以訪問?


在Swift 3中執行此操作的一種簡單方法是設置myController.showsPlaybackControls = false ,並使用按鈕或手勢識別器覆蓋整個播放器視圖。 我將它嵌入到故事板上另一個控制器的另一個視圖中,以使其變得簡單並且不會覆蓋播放器控制器。 然後訣竅是在點擊一次後隱藏按鈕,因為玩家控制器此後將跟踪點擊以顯示/隱藏控件。

@IBAction func enableControls(button:UIButton)
{
    controller?.showsPlaybackControls = true
    button.isHidden = true //The button is only needed once, then the player takes over.
}

我想我已經使用動態手勢識別器關係解決了這個問題。 該解決方案避免了自定義控件(為了保持一致性),僅使用公共API而不是子類AVPlayerViewController (明確禁止,如其他答案中所述)。

就是這樣:

  1. 創建一個嵌入AVPlayerViewController的容器視圖控制器。 (無論控件如何,這都很有用,因為您需要將播放邏輯放在某處。)

  2. 最初將showsPlaybackControls設置為false

  3. 添加UITapGestureRecognizer以識別初始點擊。

  4. 在手勢識別器的操作方法中,將showsPlaybackControls設置為true

  5. 到目前為止,它會工作,但控件會在最初的點擊時立即消失。 要解決這個問題,請將自己設置為手勢識別器的委託,實現gestureRecognizer:shouldBeRequiredToFailByGestureRecognizer:並為任何其他單擊手勢識別器返回true

這是Swift中的實際實現; 檢查andreyvit/ModalMoviePlayerViewController repo以獲取最新代碼:

import UIKit
import AVKit
import AVFoundation

public class ModalMoviePlayerViewController: UIViewController {

    private let fileName: String
    private let loop: Bool

    private var item: AVPlayerItem!
    private var player: AVPlayer!
    internal private(set) var playerVC: AVPlayerViewController!
    private var waitingToAutostart = true

    public init(fileName: String, loop: Bool = true) {
        self.fileName = fileName
        self.loop = loop
        super.init(nibName: nil, bundle: nil)
    }

    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    public override func viewDidLoad() {
        super.viewDidLoad()

        let url = NSBundle.mainBundle().URLForResource(fileName, withExtension: nil)!

        item = AVPlayerItem(URL: url)

        player = AVPlayer(playerItem: item)
        player.actionAtItemEnd = .None
        player.addObserver(self, forKeyPath: "status", options: [], context: nil)

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ModalMoviePlayerViewController.didPlayToEndTime), name: AVPlayerItemDidPlayToEndTimeNotification, object: item)

        playerVC = AVPlayerViewController()
        playerVC.player = player
        playerVC.videoGravity = AVLayerVideoGravityResizeAspectFill
        playerVC.showsPlaybackControls = false

        let playerView = playerVC.view
        addChildViewController(playerVC)
        view.addSubview(playerView)
        playerView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        playerView.frame = view.bounds
        playerVC.didMoveToParentViewController(self)

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ModalMoviePlayerViewController.handleTap))
        tapGesture.delegate = self
        view.addGestureRecognizer(tapGesture)
    }

    deinit {
        player.pause()
        player.removeObserver(self, forKeyPath: "status")
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    func togglePlayPause() {
        if isPlaying {
            pause()
        } else {
            play()
        }
    }

    func restart() {
        seekToStart()
        play()
    }

    func play() {
        if player.status == .ReadyToPlay {
            player.play()
        } else {
            waitingToAutostart = true
        }
    }

    func pause() {
        player.pause()
        waitingToAutostart = false
    }

    var isPlaying: Bool {
        return (player.rate > 1 - 1e-6) || waitingToAutostart
    }

    private func performStateTransitions() {
        if waitingToAutostart && player.status == .ReadyToPlay {
            player.play()
        }
    }

    public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        performStateTransitions()
    }

    @objc func didPlayToEndTime() {
        if isPlaying && loop {
            seekToStart()
        }
    }

    private func seekToStart() {
        player.seekToTime(CMTimeMake(0, 10))
    }

    public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if !playerVC.showsPlaybackControls {
            playerVC.showsPlaybackControls = true
        }
        super.touchesBegan(touches, withEvent: event)
    }

}

extension ModalMoviePlayerViewController: UIGestureRecognizerDelegate {

    @IBAction func handleTap(sender: UIGestureRecognizer) {
        if !playerVC.showsPlaybackControls {
            playerVC.showsPlaybackControls = true
        }
    }

    /// Prevents delivery of touch gestures to AVPlayerViewController's gesture recognizer,
    /// which would cause controls to hide immediately after being shown.
    ///
    /// `-[AVPlayerViewController _handleSingleTapGesture] goes like this:
    ///
    ///     if self._showsPlaybackControlsView() {
    ///         _hidePlaybackControlsViewIfPossibleUntilFurtherUserInteraction()
    ///     } else {
    ///         _showPlaybackControlsViewIfNeededAndHideIfPossibleAfterDelayIfPlaying()
    ///     }
    public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        if !playerVC.showsPlaybackControls {
            // print("\nshouldBeRequiredToFailByGestureRecognizer? \(otherGestureRecognizer)")
            if let tapGesture = otherGestureRecognizer as? UITapGestureRecognizer {
                if tapGesture.numberOfTouchesRequired == 1 {
                    return true
                }
            }
        }
        return false
    }

}

更新:我最終製作了自己的控件以實現更好的自定義。 這更難,但值得花時間。 請閱讀Apple的示例代碼以供參考。 它是關於實現PiP,也是關於製作自定義控件: https://developer.apple.com/library/prerelease/ios/samplecode/AVFoundationPiPPlayer/Introduction/Intro.htmlhttps://developer.apple.com/library/prerelease/ios/samplecode/AVFoundationPiPPlayer/Introduction/Intro.html

更新:點擊時,AVPlayerViewController僅觸發touchesBegan事件,而不觸發touchesEnded事件。 但它足以顯示控件。

首先,您需要隱藏控件。 在呈現AVPlayerViewController之前放置此代碼

YourAVPlayerViewController.showsPlaybackControls = false

然後繼承AVPlayerViewController並添加此函數:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    self.showsPlaybackControls = true

    super.touchesBegan(touches, withEvent: event)
}

舊污染:

我剛剛解決了這個問題。 主要思想是將UIView放在AVPlayerViewController的頂部以顯示輕擊手勢,並在不再需要時隱藏UIView。

這是代碼:

import AVKit
import UIKit

// Create a custom AVPlayerViewController
@available(iOS 8.0, *)
final class CustomAVPlayerViewController: AVPlayerViewController {

    // Create a UIView to put on top of all
    lazy var topView = UIView(frame: CGRectMake(0, 0, width, height))

    override func viewDidLoad() {
        super.viewDidLoad()

        // For sure, set it to clearcolor
        // (DON'T set alpha = 0 because it will stop receiving user interaction)
        topView.backgroundColor = UIColor.clearColor()

        // Add it to the view of AVPlayerViewController
        self.view.addSubview(topView)

        // Bring it to front
        self.view.bringSubviewToFront(topView)

        // Add a tap gesture recognizer
        topView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTap"))
    }

    // Handle the tap
    func handleTap() {

        // Show the control
        self.showsPlaybackControls = true

        // Hide the topView. You can unhide it when needed later.
        self.topView.hidden = true
    }
}

當您需要隱藏控件時,請執行以下操作:

var AVViewController = CustomAVPlayerViewController()

...

// Hide controls
AVViewController.showsPlaybackControls = false
// Show topView
AVViewController.topView.hidden = false




avplayer