使用AVPlayer播放流媒体视频

时间:2017-11-01 12:37:24

标签: ios swift macos avplayer avkit

如何使用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)
        }
    }
}

如果我运行它,应用程序不会崩溃,但我得到一个断开的链接,如下所示。

enter image description here

我在这里阅读了几十个主题。其中一个说你必须用后台线程来运行它。另一个人说URL必须以像mp4这样的文件类型结束。一个人说你不能一举投票。顺便说一句,我为macOS和iOS编写代码。所以我将这个主题留给了两个平台。感谢。

1 个答案:

答案 0 :(得分:4)

目标C

您需要三个属性,

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic,strong) AVPlayerItem * playerItem;
@property (nonatomic, strong )AVPlayerLayer *avPlayerLayer;

在视图中加载或当您想要按照方法启动播放器调用时

    -(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;
             }
        }
    }

SWIFT 3.0更新

您需要三个属性,

 var player :AVPlayer?
 var playerItem: AVPlayerItem?
 var avPlayerLayer: AVPlayerLayer?

在视图中加载或当您想要按照方法启动播放器调用时

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;
            }
        }
    }

尝试上面的代码,看看魔术:)并在主线程上完成所有这些。