How do you play a streaming video with AVPlayer
?
import Cocoa
import AVKit
class StreamViewController: NSViewController {
var videoPlayer: AVPlayer!
@IBOutlet weak var moviePlayerView: AVPlayerView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear() {
super.viewWillAppear()
}
override func viewDidAppear() {
super.viewDidAppear()
openStream()
}
func openStream() {
completeOpenStream { (done) -> (Void) in
if done {
print("done!")
}
}
}
func completeOpenStream(completionHandler: @escaping (Bool) -> (Void)) -> Void {
DispatchQueue.global().async() {
let urlString = "http://samples.mplayerhq.hu/V-codecs/h264/interlaced_crop.mp4" // You can open it with QuickTime.
let url = URL(fileURLWithPath: urlString)
let avAsset = AVURLAsset(url: url)
let playerItem = AVPlayerItem(asset: avAsset)
self.videoPlayer = AVPlayer(playerItem: playerItem)
self.moviePlayerView.player = self.videoPlayer
completionHandler(true)
}
}
}
If I run it, the app won't crash, but I get a broken link as shown below.
I have read a few dozen topics here. One of them says that you have to run it with a background thread. Another one says that a URL must end with a file type like mp4. One guy says that you can't with one down vote. By the way, I write code for both macOS and iOS. So I leave the topic for both platforms. Thanks.
SWIFT 3.0
You need three properties ,
In view did load or when you wants to start the player call following method
Then implement this method
Objective C
You need three properties ,
In view did load or when you wants to start the player call following method
Then implement this method
Try above code and see the magic :) And do all this on main thread.