Media Player框架
导入MediaPlayer.framework框架。
//声明一个媒体播放器 var moviePlayer:MPMoviePlayerController?
@IBAction func playMV() { let filePath:String? = NSBundle.mainBundle().pathForResource("namingRule", ofType: "mp4") //本地文件,使用fileURLWithPath来声明NSURL对象 moviePlayer = MPMoviePlayerController(contentURL: NSURL(fileURLWithPath: filePath!)) //如果播放网上视频,需要通过string方法来声明NSURL对象 // moviePlayer = MPMoviePlayerController(contentURL: NSURL(string: "视频网址")) //用MPMoviePlayerController做在线音乐播放 // moviePlayer = MPMoviePlayerController(contentURL: NSURL(string: "http://swift.leadingdo.com/Track08.mp3")) moviePlayer!.view.frame = self.view.frame; //设置播放器样式 moviePlayer!.controlStyle = MPMovieControlStyle.Fullscreen self.view.addSubview(moviePlayer!.view) moviePlayer!.play() //需要使用 NSNotificationCenter 类,为电影播放器添加一个观察者(observer): NSNotificationCenter.defaultCenter().addObserver(self, selector: "moviePlayerPreloadFinish:", name: MPMoviePlayerPlaybackDidFinishNotification, object: nil) }
func moviePlayerPreloadFinish(notification:NSNotification) { moviePlayer?.view.removeFromSuperview() print("播放完毕") }
播放器MPMovieControlStyle样式有3种:
None:没有播放控制控件;
Embeded:嵌入播放控制控件,没有Done按钮;
Fullscreen:全屏播放,有播放进度、Done按钮和快进等控件。