【发布时间】:2015-06-06 20:41:08
【问题描述】:
我想从一个 url 获取一个视频,并通过点击一个按钮在视图中播放它。
我有一个从 URL 播放视频的电影播放器。一切看起来都不错,但是当我单击“后退”或“下一步”按钮(即更改 ViewController)时,视频继续播放(因为我仍然能够在新屏幕上听到音频。
所以我想在 viewDidDismiss 上添加moviePlayer.Stop()。它在第一次视图更改时效果很好,但是当我回到 moviePlayer 视图并单击下一步时,我在 moviePlayer.Stop() 处发现一个 nil 错误(因为电影已经停止)。有人可以帮助我了解如何执行此操作吗?
导入 UIKit 导入媒体播放器
类 InformationViewController: UIViewController {
@IBOutlet var thumbnailImage: UIImageView!
@IBOutlet var videoPlayerView: UIView!
@IBOutlet var controlBtn: UIButton!
var moviePlayer:MPMoviePlayerController!
var url:NSURL = NSURL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")!
override func viewDidLoad() {
super.viewDidLoad()
}
func videoThumbnailIsAvailable(notification: NSNotification){
if let player = moviePlayer{
println("Thumbnail is available")
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "videoThumbnailIsAvailable:",
name: MPMoviePlayerThumbnailImageRequestDidFinishNotification,
object: nil)
/* Capture the frame at the third second into the movie */
let thirdSecondThumbnail = 3.0
/* We can ask to capture as many frames as we
want. But for now, we are just asking to capture one frame
Ask the movie player to capture this frame for us */
moviePlayer.requestThumbnailImagesAtTimes([thirdSecondThumbnail],
timeOption: .NearestKeyFrame)
/* Now get the thumbnail out of the user info dictionary */
let thumbnail =
notification.userInfo![MPMoviePlayerThumbnailImageKey] as? UIImage
if let imageR = thumbnail{
/* We got the thumbnail image. You can now use it here */
println("Thumbnail image = \(imageR)")
//println(UIImage(data: imageR))
thumbnailImage.image = imageR
}
}
}
@IBAction func controlBtn(sender: AnyObject) {
controlBtn.alpha = 0
moviePlayer = MPMoviePlayerController(contentURL: url)
let frameWidth = self.videoPlayerView.frame.size.width
let frameHeight = self.videoPlayerView.frame.size.height
//moviePlayer.view.frame = CGRect(x: 24, y: 18, width: frameWidth, height: frameHeight)
self.videoPlayerView.addSubview(moviePlayer.view)
// Send button backword
self.videoPlayerView.sendSubviewToBack(moviePlayer.view)
moviePlayer.fullscreen = false
moviePlayer.controlStyle = MPMovieControlStyle.Embedded
// Pure Visual Format Language style (http://stackoverflow.com/questions/26180822/swift-adding-constraints-programmatically)
(moviePlayer.view).setTranslatesAutoresizingMaskIntoConstraints(false)
let views = ["view": videoPlayerView, "videoView": moviePlayer.view]
var constH = NSLayoutConstraint.constraintsWithVisualFormat("H:[view]-(<=0)-[videoView(\(frameWidth))]", options: .AlignAllCenterY, metrics: nil, views: views)
view.addConstraints(constH)
var constW = NSLayoutConstraint.constraintsWithVisualFormat("V:[view]-(<=0)-[videoView(\(frameHeight))]", options: .AlignAllCenterX, metrics: nil, views: views)
view.addConstraints(constW)
}
override func viewDidDisappear(animated: Bool) {
moviePlayer.stop()
}
}
任何帮助将不胜感激。 谢谢。
【问题讨论】: