简体   繁体   中英

How to use AVQueuePlayer?

I want to play a set of video files from a remote server on iOS. I don't want to use an HLS playlist.

I am trying to use 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. When I check the player.items() array after a few seconds, there is nothing there.

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 :)

The problem may be with your media. AVPlayer on iOS does not support playing .ts files directly. Those must be contained within an HLS playlist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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