美文网首页
iOS开发swift -- PLPlayer的使用

iOS开发swift -- PLPlayer的使用

作者: Hayley__ | 来源:发表于2017-08-07 17:52 被阅读713次

一 PLPlayer 介绍

PLPlayerKit 是一个适用于 iOS 的 HLS 及 RTMP 播放 SDK,可高度定制化和二次开发。特色是支持 RTMP 协议下 H.264 编码 FLV 封装的多媒体流的播放,针对与用户体验密切相关的首开缓冲时间进行了优化,另外还根据移动网络的多变性以及直播场景对播放实时性的需求提供了跳帧机制。
官方链接

二 sdk集成 CocoaPods

$ cd/你的项目地址
$ pod init
$ open -a Xcode Podfile

platform :ios, '9.0'
target '你的项目' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!
  pod 'SnapKit', '~> 3.2.0'
  pod 'PLPlayerKit', '~> 2.4.3'
end
$ pod install

三 相关配置

在info.plist中加入安全域名白名单(右键info.plist用source code打开)
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    //允许后台播放
    <key>UIBackgroundModes</key>
    <array>
        <string>audio</string>
    </array>

四 代码示例

    func createView()
    {
        //初始化 PLPlayerOption 对象 可以更改需要修改的 option 属性键所对应的值
        let option = PLPlayerOption.default()
        option.setOptionValue(15, forKey: PLPlayerOptionKeyTimeoutIntervalForMediaPackets)
        let url:URL = NSURL.init(string: "http://vod.dev")! as URL
        //初始化 PLPlayer
        player = PLPlayer.init(url: url, option: option)
        player.launchView?.image = UIImage.init(named: "backImage")
        player.delegate = self
        player.isBackgroundPlayEnable = true
        try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        //获取视频输出视图并添加为到当前 UIView 对象的 Subview
        view.addSubview(player.playerView!)
        
        player.playerView?.snp.makeConstraints({ (make) in
            make.top.equalTo(view).offset(80)
            make.left.right.equalTo(view)
            make.height.equalTo(200)
        })
        
        button = UIButton.init(type: .custom)
        button.setTitle("播放", for: .normal)
        button.setTitleColor(UIColor.red, for: .normal)
        button.addTarget(self, action: #selector(buttonclick(button:)), for: .touchUpInside)
        view.addSubview(button)
        
        button.snp.makeConstraints { (make) in
            make.centerX.centerY.equalTo(view)
        }
    }

    func buttonclick(button:UIButton)  {
        if button.isSelected {
            player.seek(to: player.currentTime)
            button.setTitle("暂停", for: .normal)
        }else
        {
            player.stop()
            button.setTitle("播放", for: .normal)
        }
        button.isSelected = !button.isSelected
    }

    // 实现 <PLPlayerDelegate> 来控制流状态的变更
    func player(_ player: PLPlayer, stoppedWithError error: Error?) {
        // 当发生错误时,会回调这个方法
    }
    
    func player(_ player: PLPlayer, statusDidChange state: PLPlayerStatus) {
        // 这里会返回流的各种状态,你可以根据状态做 UI 定制及各类其他业务操作
        // 除了 Error 状态,其他状态都会回调这个方法
    }

相关文章

网友评论

      本文标题:iOS开发swift -- PLPlayer的使用

      本文链接:https://www.haomeiwen.com/subject/ygpalxtx.html