简体   繁体   English

AVPlayerViewController 花了太多时间来自动播放视频/音频 automaticallyWaitsToMinimizeStalling

[英]AVPlayerViewController took too much time to play video/audio with automaticallyWaitsToMinimizeStalling

I am using AVPlayer, in Player I want to play video from the Server.我正在使用 AVPlayer,我想在播放器中播放来自服务器的视频。 I am doing like the code below.我正在做下面的代码。 Problem I am facing is I set the我面临的问题是我设置了

automaticallyWaitsToMinimizeStalling = true

According to Documentation 根据文档

A Boolean value that indicates whether the player should automatically delay playback in order to minimize stalling.一个 Boolean 值,指示播放器是否应自动延迟播放以尽量减少停顿。

but it took too much time to load the video/audio, for 8minutes video it took almost 2 to 3 minutes wait to play.但是加载视频/音频花费了太多时间,8分钟的视频几乎需要等待2到3分钟才能播放。 If during this time (wait time of 2 to 3 minutes), user pause the video and play again, then video will play without any delay.如果在此期间(等待时间为 2 到 3 分钟),用户暂停视频并再次播放,则视频将无任何延迟地播放。 This unnecessary wait should not be happened.这种不必要的等待是不应该发生的。

Can anyone guide me how to decrease wait of stalling?谁能指导我如何减少停滞等待? I can not use this answer我不能使用这个答案

player.automaticallyWaitsToMinimizeStalling = false

because due to set this value false, my player stops again and again, and user have to play this manually, so this thing is very bad.因为把这个值设置为false,我的播放器一次又一次地停止,用户必须手动播放,所以这个东西很糟糕。

// MARK: - Outlets
    @IBOutlet weak var audioView: UIView!

// MARK: - Variables
    var player: AVPlayer = AVPlayer()
    let playerController = AVPlayerViewController()
    var obs = Set<NSKeyValueObservation>()


// MARK: - Helper Method
private func settingForAudioPlayer() {
    guard let lesson = viewModal.lesson else {
        print("lesson not found")
        return
    }
    var path = "\(Server.audioVideoBasurl + (lesson.videoPath ?? ""))"
    path = path.replacingOccurrences(of: " ", with: "%20")
    print("path:\(path)")
    guard let url = URL(string: path) else {
        print("Path not converted to url")
        return
    }
    self.player = AVPlayer(url: url)
    self.player.automaticallyWaitsToMinimizeStalling = true
self.player.playImmediately(atRate: 1.0)

    self.playerController.player = self.player
    DispatchQueue.main.async {
        
        self.playerController.view.clipsToBounds = true
        self.playerController.view.removeFromSuperview()
        self.playerController.delegate = self

        self.showSpinner(onView: self.audioView, identifier: "audioView", title: "")
        self.audioView.addSubview(self.playerController.view)
        self.audioView.layoutIfNeeded() // Previously we were playing only audio but after some time we decided to add videos also so thats why that view name is audioView Don’t get confuse with this view name
        self.playerController.view.frame.size.width = self.audioView.frame.width
        self.playerController.view.frame.size.height = self.audioView.frame.height
        self.playerController.view.backgroundColor = .clear
        self.playerController.videoGravity = AVLayerVideoGravity.resizeAspectFill

        var ob : NSKeyValueObservation!
        ob = self.playerController.observe(\.isReadyForDisplay, options: [.initial, .new]) { vc, ch in
            guard let ok = ch.newValue, ok else {return}
            self.obs.remove(ob)
            DispatchQueue.main.async {
                print("finishing")
                self.removeSpinner(identifier: "audioView") // This is my Custom Method
                vc.view.isHidden = false // The Idea of KVO observer add got from the Internet
            }
        }
        self.obs.insert(ob)
        let iv = self.audioBackgroundImageView ?? UIImageView()

        let v = self.playerController.contentOverlayView!
        iv.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            iv.bottomAnchor.constraint(equalTo:v.bottomAnchor),
            iv.topAnchor.constraint(equalTo:v.topAnchor),
            iv.leadingAnchor.constraint(equalTo:v.leadingAnchor),
            iv.trailingAnchor.constraint(equalTo:v.trailingAnchor),
        ])

        NSLayoutConstraint.activate([
            v.bottomAnchor.constraint(equalTo:self.playerController.view.bottomAnchor),
            v.topAnchor.constraint(equalTo:self.playerController.view.topAnchor),
            v.leadingAnchor.constraint(equalTo:self.playerController.view.leadingAnchor),
            v.trailingAnchor.constraint(equalTo:self.playerController.view.trailingAnchor),
        ])

        self.view.layoutIfNeeded()
    }

}

in Above peace of code I have video url (Path), I passed it to the AVPlayer, Player pass to AVPlayerController, add observer to the playerController to check that AVPlayerController is ready for Display, then remove observer.在上面的和平代码中,我有视频 url(路径),我将它传递给 AVPlayer,Player 传递给 AVPlayerController,将观察者添加到 playerController 以检查 AVPlayerController 是否准备好显示,然后删除观察者。 After that I am only settings the constraint.之后我只设置约束。

Kindly guide me how to decrease the waits on swift, on Android side video/Audio plays with in seconds.请指导我如何减少 swift、Android 侧视频/音频播放的等待时间。 It can be duplicate of this but my scenario is different and the solution here did not work for me.它可以重复,但我的情况不同,这里的解决方案对我不起作用。 Kindly let me know in-case you need more information to help me.如果您需要更多信息来帮助我,请告诉我。

If you don't want to use automaticallyWaitsToMinimizeStalling = true you can also observe player buffer and decide whether you start playing video.如果你不想使用automaticallyWaitsToMinimizeStalling = true你也可以观察播放器缓冲区并决定是否开始播放视频。 Here are some steps how to do that:以下是如何执行此操作的一些步骤:

  1. Create observer variable in the class where you intend to handle player:在您打算处理玩家的 class 中创建观察者变量:

     var playbackBufferEmptyObserver: NSKeyValueObservation? var playbackBufferFullObserver: NSKeyValueObservation? var playbackLikelyToKeepUpObserver: NSKeyValueObservation?
  2. Instantiate AVPlayer with AVPlayerItem instead of URL likewise:同样使用AVPlayerItem而不是URL实例化AVPlayer

     let playerItem = AVPlayerItem(url: url) let player = AVPlayer(playerItem: playerItem)
  3. Create observers and assign them to variables:创建观察者并将它们分配给变量:

     playbackBufferEmptyObserver = self.playerItem.observe(\.isPlaybackBufferEmpty, options: [.new, .initial ], changeHandler: { [weak self] (player, bufferEmpty) in if let self = self { DispatchQueue.main.async { if bufferEmpty.newValue == true { // handle showing loading, player not playing } } } }) playbackBufferFullObserver = self.playerItem.observe(\.isPlaybackBufferFull, options: [.new, .initial], changeHandler: {[weak self] (player, bufferFull) in if let self = self { DispatchQueue.main.async { if bufferFull.newValue == true { //handle when player buffer is full (eg hide loading) start player } } } }) playbackLikelyToKeepUpObserver = self.playerItem.observe(\.isPlaybackLikelyToKeepUp, options: [.new, .initial], changeHandler: { [weak self] (player, _) in if let self = self { if ((self.playerItem?.status?? AVPlayerItem.Status.unknown). ==.readyToPlay) { // handle that player is ready to play (eg, hide loading indicator, start player) } else { // player is not ready to play yet } } })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Swift 中使用 AVPlayerViewController (AVKit) 播放视频 - How to play video with AVPlayerViewController (AVKit) in Swift 同时录制视频和播放音频ios - Record Video and play audio at same time ios 使用AVPlayer和AVPlayerViewController,但不存在音频和视频 - Using AVPlayer and AVPlayerViewController, but audio and video not present 无法使用AVPlayerViewController在iPad上播放视频文件 - Not able to play video file on iPad using AVPlayerViewController 从UITableViewController更改视频以在AVPlayerViewController中播放 - Change the video to play in AVPlayerViewController from UITableViewController 在IOS中同时播放音频和视频 - Play audio and video at the same time in IOS 在iPhone中播放SoundCloud曲目需要花费太多时间 - SoundCloud tracks take too much time play in iPhone 为什么我找不到使用AVPlayerViewController播放视频的方法 - Why I can't find a way to play video with AVPlayerViewController 如何在MPMovieplayer中的用户指定时间范围内播放音频/视频 - How to play audio/video within user specified time frame in MPMovieplayer AVPlayerViewController视频的音频背景播放,并支持多种格式 - AVPlayerViewController video's audio background playing and support for multiple formats
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM