我在这里用来从图库中选择/加载视频。我尝试使用imageview在屏幕上显示预览。但无法在屏幕上显示我选择的视频作为预览。
这是我的代码:
import UIKit
import AVFoundation
import MobileCoreServices
import AssetsLibrary
import MediaPlayer
import CoreMedia
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var firstAsset: AVAsset?
var loadingAssetOne = false
@IBOutlet weak var imgView: UIImageView!
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func savedPhotosAvailable() -> Bool {
if UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) == false {
let alert = UIAlertController(title: "Not Available", message: "No Saved Album found", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
return false
}
return true
}
@IBAction func playvideo(sender: AnyObject) {
if savedPhotosAvailable() {
loadingAssetOne = true
startMediaBrowserFromViewController(self, usingDelegate: self)
}
}
func startMediaBrowserFromViewController(viewController: UIViewController, usingDelegate delegate: protocol<UINavigationControllerDelegate, UIImagePickerControllerDelegate>) -> Bool {
// 1
if UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) == false {
return false
}
// 2
//var mediaUI = UIImagePickerController()
imagePicker.sourceType = .SavedPhotosAlbum
imagePicker.mediaTypes = [kUTTypeMovie as String]
imagePicker.allowsEditing = true
imagePicker.delegate = delegate
// 3
presentViewController( imagePicker, animated: true, completion: nil)
return true
}
// MARK: - UIImagePickerControllerDelegate Methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imgView.contentMode = .ScaleAspectFit
imgView.image = pickedImage
}
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
}
需要显示我的视频,如下图所示:
请帮帮我。我需要将我选择的视频显示为预览,如果我触摸它应该在同一个屏幕上播放。我正在显示的视频应该像我上面图像中显示的图像视频预览一样。
谢谢!
答案 0 :(得分:0)
您必须使用UIView并创建AVPlayerLayer。
因此,而不是你的imgView创建一个UIView并将UIView类设置为自定义类,如下所示。
import UIKit
import AVFoundation
class PlayerView: UIView {
var player: AVPlayer? {
get {
return playerLayer.player
}
set {
playerLayer.player = newValue
}
}
var playerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
override class func layerClass() -> AnyClass {
return AVPlayerLayer.self
}
}