您的位置:首页 > 产品设计 > 产品经理

视频播放(MPMediaPlayerController,AVPlayer,AVPlayerViewcontroller) for iOS

2015-10-27 15:13 489 查看
和音频播放一样,ios也提供个很多的API。如mediaPlayer.framework下的MPMediaPlayerController、AVFounditon.framework下的AVPlayer和AVKit下的AVPlayerViewcontroller。下面先看一下下图







有上面的三幅图可以看出,MPMovieplayerController已经在ios9.0中被废弃了,用来替代的是AVPlayerViewcontroller。尽管如此,但还是说一下比较熟悉的MPMovieplayerController.

1、MPMovieplayerController

<1>初始化MPMovieplayerController

// 创建本地URL(也可创建基于网络的URL)
NSURL* movieUrl = [[NSBundle
mainBundle]URLForResource:@"movie"
withExtension:@"mp4"];

// 使用指定URL创建MPMoviePlayerController

// MPMoviePlayerController将会播放该URL对应的视频

MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController
alloc] initWithContentURL:movieUrl];

<2>设置属性

/ 设置该播放器的控制条风格。

moviePlayer.controlStyle =
MPMovieControlStyleEmbedded;

// 设置该播放器的缩放模式

moviePlayer.scalingMode =
MPMovieScalingModeAspectFit;

<3>设置view的frame并添加到window上

[moviePlayer.view
setFrame: CGRectMake(0 ,
0 ,
380 , 320)];

[self.movieView
addSubview:
moviePlayer.view];

<4>播放暂停和停止

[moviePlayer
play];

[moviePlayer
pause];

[moviePlayer
stop];

由于属性太多,这里只列出能完成简单的播放器的属性,其他属性可在头文件中查找。

2、AVPlayer

AVPlayer既可以播放音乐又可以播放视频;使用AVPlayer不能直接显示视频,必须要加入AVPlayerLayer中,并添加到其他能显示的layer中。

NSString *filePath = [[NSBundle
mainBundle] pathForResource:@"backspace"
ofType:@"mov"];

NSURL *sourceMovieURL = [NSURL
fileURLWithPath:filePath];

AVAsset *movieAsset
= [AVURLAsset
URLAssetWithURL:sourceMovieURL options:nil];

AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];

AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];

AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];

playerLayer.frame = self.view.layer.bounds;

playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;

[self.view.layer
addSublayer:playerLayer];

[player play];

3、AVPlayerViewcontroller
AVPlayerViewcontroller继承自UIViewController,一般适用于点击一个视频缩略图,modal出一个新的界面来进行播放的情况。

用法:

AVPlayerViewController *player = [[AVPlayerViewController
alloc]init];
player.player = [[AVPlayer
alloc]initWithURL:movieUrl];
[self
presentViewController:player
animated:YES
completion:nil];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: