AVPlayer
AVPlayer is intended for playing a single media asset at a time. The player instance can be reused to play additional media assets using its replaceCurrentItem(with:) method, but it manages the playback of only a single media asset at a time. The framework also provides a subclass of AVPlayer, called AVQueuePlayer, that you can use to create and manage of queue of media assets to be played sequentially.
一个本地、远程音视频播放器,简单好用
//AVAsset (本地路径或者网络链接)
let asset = AVAsset.init(url: URL.init(fileURLWithPath: filePath))
//AVPlayerItem
let playItem = AVPlayerItem.init(asset: asset, automaticallyLoadedAssetKeys: ["tracks","duration","commonMetadata"])
//AVPlayer
let player = AVPlayer.init(playerItem: playItem)
//监听实时进度
player.addPeriodicTimeObserver(forInterval: CMTime.init(value: 1, timescale: 1), queue: DispatchQueue.main) { (time) in
print("time = \(time.value)")
}
//AVPlayerLayer(添加到内容区的layer)
let playerLayer = AVPlayerLayer.init(player: player)
playerLayer.frame = view.bounds
view.layer.addSublayer(playerLayer)
//监听视频加载状态变化
playItem.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: &playerContext)
//监听视频播放进度
NotificationCenter.default.addObserver(self, selector: #selector(handleItemFinish), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: playItem)
监听视频加载状态变化
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let playItem = object as? AVPlayerItem{
switch playItem.status{
case .readyToPlay:
player.play()
player.addPeriodicTimeObserver(forInterval: CMTimeMake(1, 1), queue: DispatchQueue.global()) { (time) in
}
default:
print("not readyToPlay")
}
}
}
监听视频播放进度
@objc func handleItemFinish(notification:Notification){
player.seek(to: kCMTimeZero)
}
音量条
let voloumView = MPVolumeView.init(frame: CGRect.init(x: (view.frame.size.width-200)*0.5, y: 450, width: 200, height: 100))
voloumView.showsRouteButton = false
voloumView.showsVolumeSlider = true
voloumView.sizeToFit()
view.addSubview(voloumView)
for subview in voloumView.subviews{
if NSStringFromClass(subview.classForCoder) == "MPVolumeSlider"{
if let slider = subview as? UISlider{
slider.sendActions(for: UIControlEvents.touchUpInside)
slider.thumbTintColor = UIColor.yellow;
}
}
}
参考链接:AVPlayer
网友评论