简体   繁体   English

如何使用 AVQueuePlayer?

[英]How to use AVQueuePlayer?

I want to play a set of video files from a remote server on iOS.我想从 iOS 上的远程服务器播放一组视频文件。 I don't want to use an HLS playlist.我不想使用 HLS 播放列表。

I am trying to use AVQueuePlayer.我正在尝试使用 AVQueuePlayer。 Here's how I initialize it:这是我初始化它的方法:

let url = URL(string: "https://example.com/video.ts")! // 10 second video
let item = AVPlayerItem(url: url)
let player = AVQueuePlayer(items: [item])
player.play()

When I show this player on screen, using an AVPlayerLayer and a custom view or with an AVPlayerViewController, it just shows a loading icon and no content.当我在屏幕上显示此播放器时,使用 AVPlayerLayer 和自定义视图或使用 AVPlayerViewController,它只显示加载图标而没有内容。 When I check the player.items() array after a few seconds, there is nothing there.当我几秒钟后检查player.items()数组时,那里什么也没有。

Is it the expected behavior?这是预期的行为吗? How to accomplish my task?如何完成我的任务?

Well, let me think the code is something like this.好吧,让我认为代码是这样的。

import UIKit
import AVFoundation

class ViewController: UIViewController {

    private var player: AVQueuePlayer?
    private var playerLayer: AVPlayerLayer?

    override func viewDidLoad() {
        super.viewDidLoad()
        super.view.backgroundColor = UIColor.lightGray

        // Video file for demo
        let mediaPath = URL(fileURLWithPath:Bundle.main.path(forResource: "ChoppedBipBop", ofType: "m4v")!)

        startDemoVideo(videoURL: mediaPath)
    }

    public func startDemoVideo(videoURL: URL) {
        player = AVQueuePlayer()
        playerLayer = AVPlayerLayer(player: player)

        guard let playerLayer = playerLayer else { fatalError("Error creating player layer") }
        playerLayer.frame = view.layer.bounds
        view.layer.addSublayer(playerLayer)

        let videoAsset = AVURLAsset(url: videoURL)

        videoAsset.loadValuesAsynchronously(forKeys: ["duration", "playable"]) {

            DispatchQueue.main.async {
                let loopItem = AVPlayerItem(asset: videoAsset)
                self.player?.insert(loopItem, after: nil)

                self.player?.play()
            }
        }
    }

}

EDIT: I put all my code used for the demo I have a local file video, so you need to replace with an URL request object, if you want to test you can make a Single View App project with Swift and replace this in your ViewController and then build and run :)编辑:我把我所有用于演示的代码都放在我有一个本地文件视频,所以你需要用一个 URL 请求对象替换,如果你想测试你可以用 Swift 创建一个单视图应用程序项目并在你的 ViewController 中替换它然后构建并运行:)

The problem may be with your media.问题可能出在您的媒体上。 AVPlayer on iOS does not support playing .ts files directly. iOS 上的AVPlayer不支持直接播放.ts文件。 Those must be contained within an HLS playlist.这些必须包含在 HLS 播放列表中。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM