0

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?

Daniel Ryan
  • 6,976
  • 5
  • 45
  • 62
adsalpha
  • 102
  • 2
  • 10

2 Answers2

1

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

Ladd.c
  • 973
  • 11
  • 11
0

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.

Fabian
  • 6,973
  • 2
  • 26
  • 27