1.播放器
var movieConntroller:MPMoviePlayerController?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
let filePath = Bundle.main.path(forResource: "xwydq", ofType: "mp4")
//print("filePath \(String(describing: filePath))")
if( filePath != nil ){
self.movieConntroller = MPMoviePlayerController(contentURL: URL(fileURLWithPath: filePath!))
self.movieConntroller!.view.frame = CGRect(x: 20, y: 20, width: 300, height: 200)
self.movieConntroller!.view.backgroundColor = UIColor.brown
// self.movieConntroller!.controlStyle = .fullscreen
self.movieConntroller?.scalingMode = .fill
//moviePlayerViewController = MPMoviePlayerViewController(contentURL: URL(fileURLWithPath: filePath))
//添加手势
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(self.movielongPress(gesture:)))
self.movieConntroller!.view.addGestureRecognizer(longPress)
let movieDoubleTap = UITapGestureRecognizer(target: self, action: #selector(self.movieDoubleTap(gesture:)))
movieDoubleTap.numberOfTapsRequired = 2
self.movieConntroller!.view.addGestureRecognizer(movieDoubleTap)
self.view.addSubview(self.movieConntroller!.view!)
//添加滑动手势,改变媒体音量
let mpVolume:MPVolumeView = MPVolumeView(frame: self.view.bounds)
mpVolume.isHidden = true
mpVolume.isUserInteractionEnabled = true
mpVolume.showsVolumeSlider = false
self.view.addSubview(mpVolume)
for sliderView in mpVolume.subviews{
print("sliderView=\(sliderView)")
if (sliderView.isKind(of: NSClassFromString("MPVolumeSlider")!)) {
self.volumeSlider = sliderView as! UISlider
}
}
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.volumeSlider(gesture:)))
self.movieConntroller?.view.addGestureRecognizer(panGesture)
self.movieConntroller?.play()
}
}
2.监听播放状态
required init?(coder: NSCoder) {
super.init(coder: coder)
//监听状态切换
NotificationCenter.default.addObserver(self, selector: #selector(self.moviePlayerNotifcation(info:)), name: NSNotification.Name.MPMoviePlayerDidEnterFullscreen, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.moviePlayerNotifcation(info:)), name: NSNotification.Name.MPMoviePlayerDidExitFullscreen, object: nil)
}
@objc func moviePlayerNotifcation(info:Notification){
print("\(info.name)")
switch info.name {
case NSNotification.Name.MPMoviePlayerDidEnterFullscreen:
self.movieConntroller?.play()
case NSNotification.Name.MPMoviePlayerDidExitFullscreen:
self.movieConntroller?.pause()
default:
self.movieConntroller?.stop()
}
}
- AVPlayerViewController
var avPlayer:AVPlayerViewController?
var player:AVPlayerItem?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
let filePath = Bundle.main.path(forResource: "xwydq", ofType: "mp4")
if( filePath != nil ){
self.avPlayer = AVPlayerViewController()
self.avPlayer?.view.frame = CGRect(x: 20, y: 20, width: 250, height: 200)
self.avPlayer?.view.backgroundColor = UIColor.blue
self.player = AVPlayerItem(url: URL(fileURLWithPath: filePath!))
self.avPlayer?.player = AVPlayer(playerItem: self.player)
self.view.addSubview(self.avPlayer!.view!)
self.avPlayer?.player?.play()
}
}
4.调用相机录制视频或者选择媒体库
实现代理 UIImagePickerControllerDelegate,UINavigationControllerDelegate
@IBAction func openCamera(_ sender: Any) {
//判断是否有相机
if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
print("没有相机")
return
}else {
self.imagePickerControllerStatus(imageStatus: UIImagePickerController.SourceType.camera)
}
}
func imagePickerControllerStatus(imageStatus:UIImagePickerController.SourceType){
let videoPicker = UIImagePickerController()
videoPicker.delegate = self
videoPicker.sourceType = imageStatus
videoPicker.mediaTypes = [ kUTTypeMovie as String ]
if (imageStatus == UIImagePickerController.SourceType.camera){
self.videoRecorder(imagePick: videoPicker)
}
videoPicker.allowsEditing = true
self.present(videoPicker, animated: true, completion: nil)
}
func videoRecorder(imagePick :UIImagePickerController){
imagePick.videoMaximumDuration = 30
imagePick.videoQuality = .typeMedium
}
//重写代理方法
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let paths:NSArray = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) as NSArray
let documentPath:String = paths.firstObject as! String
var filePath = documentPath.appending("/video.mov")
let infoDictionary:NSDictionary = info as NSDictionary
let stateStr:NSString = infoDictionary.object(forKey: UIImagePickerController.InfoKey.mediaType) as! NSString
if stateStr.isEqual(to: kUTTypeMovie as String){
var movieUrl:NSURL!
// let mediaUrl:NSURL = infoDictionary.object(forKey: UIImagePickerController.InfoKey.mediaURL) as! NSURL
//let mediaUrlString = mediaUrl.absoluteString
movieUrl = (infoDictionary.object(forKey: UIImagePickerController.InfoKey.mediaURL) as! NSURL)
do{
let mediaData:NSData = try NSData(contentsOf: movieUrl as URL)
if FileManager.default.fileExists(atPath: filePath){
let dateFormatter:DateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH-mm"
let dateStr = dateFormatter.string(from: Date())
let fileName = "/video-\(dateStr).mov"
filePath = documentPath.appending(fileName)
}
do{
try mediaData.write(toFile: filePath, options: NSData.WritingOptions.atomic)
//播放视频
if self.movieConntroller != nil {
self.movieConntroller!.stop()
self.movieConntroller!.contentURL = URL(fileURLWithPath: filePath)
self.movieConntroller!.play()
}else{
self.player = AVPlayerItem(url: URL(fileURLWithPath: filePath))
self.avPlayer?.player = AVPlayer(playerItem: self.player)
self.avPlayer?.player?.play()
}
self.dismiss(animated: true, completion: nil)
}catch {
let alert:UIAlertController = UIAlertController(title: "警告", message: "当前movie error", preferredStyle: UIAlertController.Style.alert)
self.present(alert, animated: true, completion: nil)
}
}catch{
print("数据格式错误")
}
}
}
@IBAction func openPhoto(_ sender: Any) {
self.imagePickerControllerStatus(imageStatus: UIImagePickerController.SourceType.photoLibrary)
}
5.自定义View和封装view
class MovieCoustomPlayerView : UIView{
var shapeLayer = CAShapeLayer()
required init?(coder: NSCoder) {
super.init(coder: coder)
self.initializeShapeLayer(superView: self, superViewWidth: frame.width, superViewHeight: frame.height)
let playerTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.playAnimationGesture(gesture:)))
self.isUserInteractionEnabled = true
self.addGestureRecognizer(playerTap)
}
@objc func playAnimationGesture(gesture:UITapGestureRecognizer){
/*print("playAnimationGesture")
self.shapeLayer.animationBasicKey(animationName: "strokeEnd", fromValue: NSNumber(value: 0 ), toValue: NSNumber(value: 1)) { animationReturenIsGrouop in
animationReturenIsGrouop.duration = 1
return false
}*/
self.shapeLayer.animationBasicKey(animationName: "strokeEnd", fromValue: NSNumber(value: 1 ), toValue: NSNumber(value: 0)) { animationReturenIsGrouop in
animationReturenIsGrouop.duration = 1
return false
}
}
func initializeShapeLayer(superView:UIView,superViewWidth:CGFloat , superViewHeight:CGFloat){
self.shapeLayer.strokeColor = UIColor(red: CGFloat(16.0/255.0), green: CGFloat(99.0/255.0), blue: CGFloat(233.0/255.0), alpha: CGFloat(1)).cgColor
self.shapeLayer.strokeStart = 0
self.shapeLayer.strokeEnd = 1
self.shapeLayer.lineWidth = 5
self.shapeLayer.fillColor = UIColor.clear.cgColor
self.shapeLayer.lineJoin = .round
self.shapeLayer.lineCap = .round
let playerPath:UIBezierPath = UIBezierPath()
playerPath.move(to: CGPoint(x: 5, y: superViewHeight-5))
playerPath.addLine(to: CGPoint(x: superViewWidth - 5, y: superViewHeight/2 - 5))
playerPath.addLine(to: CGPoint(x: 5, y: 5))
playerPath.addLine(to: CGPoint(x: 5, y: superViewHeight*0.7-5 ))
self.shapeLayer.path = playerPath.cgPath
self.layer.addSublayer(self.shapeLayer)
}
}
import UIKit
extension CALayer {
func animationBasicKey(animationName:NSString,fromValue:AnyObject,toValue:AnyObject,animationBlock:((_ animationReturenIsGrouop:CABasicAnimation)->Bool)!){
self.setValue(toValue, forKey: animationName as String)//保持动画结束后的状态
let animationObject:CABasicAnimation = CABasicAnimation(keyPath: animationName as String)
animationObject.fromValue = fromValue
animationObject.toValue = toValue
var isGroup:Bool = false
if (animationBlock != nil) {
isGroup = animationBlock(animationObject)
}
if (!isGroup){//非组动画就直接添加
self.add(animationObject, forKey: animationName as String)
}
}
}
import UIKit
import AVFoundation
protocol MoviePlayerDelegate : NSObjectProtocol{
func videoDidPlay(currentTime:Float64,duration:Float64)
}
class MoviePlayer :UIView{
var player:AVPlayer = AVPlayer()
//数据
var playerItem:AVPlayerItem?// = AVPlayerItem(url: URL(fileURLWithPath: ""))
weak var delegate:MoviePlayerDelegate?
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func initialzeAVPlayer(filePath:String){
let avAsset:AVAsset = AVAsset(url: URL(fileURLWithPath: filePath))
self.playerItem = AVPlayerItem(asset: avAsset)
//替换数据源
self.player.replaceCurrentItem(with: self.playerItem)
let playerPlayLayer:AVPlayerLayer = self.layer as! AVPlayerLayer
playerPlayLayer.player = self.player
playerPlayLayer.videoGravity = .resizeAspect
weak var weekObject:MoviePlayer? = self
// Invoke callback every half second
let interval = CMTime(seconds: 1,
preferredTimescale: CMTimeScale(USEC_PER_SEC))
//监听时间变化
self.player.addPeriodicTimeObserver(forInterval: interval, queue: nil) { _ in
let duration:Float64 = CMTimeGetSeconds(weekObject!.playerItem!.duration)
let currentTime:Float64 = CMTimeGetSeconds(weekObject!.playerItem!.currentTime())
weekObject!.delegate?.videoDidPlay(currentTime: currentTime, duration: duration)
}
}
func play(){
self.player.play()
}
func pause(){
self.player.pause()
}
override class var layerClass: AnyClass{
return AVPlayerLayer.self
}
}










网友评论