问题描述
如何使用AVPlayer
播放流式视频?
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.
我在这里阅读了几十个主题.其中之一说,您必须使用后台线程来运行它.另一个人说,URL必须以mp4之类的文件类型结尾.一个人说你不能投反对票.顺便说一下,我为macOS和iOS都编写了代码.因此,我将话题保留在两个平台上.谢谢.
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
您需要三个属性,
var player :AVPlayer?
var playerItem: AVPlayerItem?
var avPlayerLayer: AVPlayerLayer?
在视图中确实已加载或您要按照以下方法启动播放器调用
In view did load or when you wants to start the player call following method
func startplayer(){
playerItem = AVPlayerItem.init(url: URL.init(string: "https:yourUrl.com")!)
player = AVPlayer.init(playerItem: playerItem)
player?.allowsExternalPlayback = true
avPlayerLayer = AVPlayerLayer.init(player: player)
avPlayerLayer?.frame = CGRect.init(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
avPlayerLayer?.videoGravity = .resizeAspect
view.layer.insertSublayer(avPlayerLayer!, at: 0)
player?.currentItem?.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
}
然后实现此方法
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let currentPlayer = player , let playerObject = object as? AVPlayerItem, playerObject == currentPlayer.currentItem, keyPath == "status"
{
if ( currentPlayer.currentItem!.status == .readyToPlay)
{
currentPlayer.play()
currentPlayer.rate = 1.0;
}
}
}
目标C
您需要三个属性,
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic,strong) AVPlayerItem * playerItem;
@property (nonatomic, strong )AVPlayerLayer *avPlayerLayer;
在视图中确实已加载或您要按照以下方法启动播放器调用
In view did load or when you wants to start the player call following method
-(void) startplayer
{
AVPlayerItem * playerItem= [AVPlayerItem playerItemWithURL:@"https:yourUrl.com"];
self.player = [AVPlayer playerWithPlayerItem:playerItem];
self.player.allowsExternalPlayback= YES;
self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
self.avPlayerLayer.frame = CGRectMake(OriginX, OriginY, self.view.frame.size.width, self.view.frame.size.height);
self.avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
[self.view.layer insertSublayer:self.avPlayerLayer atIndex:FirstIndex];
[self.player.currentItem addObserver:self
forKeyPath:@"status"
options:0
context:nil];
}
然后实现此方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (object == self.player.currentItem && [keyPath isEqualToString:@"status"])
{
if (self.player.currentItem.status == AVPlayerStatusReadyToPlay)
{
[self.player play];
self.player.rate = 1.0;
}
}
}
尝试上面的代码,看看魔术:)并在主线程上完成所有这些操作.
Try above code and see the magic :) And do all this on main thread.
这篇关于使用AVPlayer播放流视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!