1.引入系统框架
2.创建视频的url
3.创建播放项目
4.初始化播放器
5.设置播放页面
//引入系统文件 #import <AVFoundation/AVFoundation.h> #import <AVKit/AVKit.h> @interface ViewController () /** * 控制视频播放的控件 */ @property (weak, nonatomic) IBOutlet UISlider *progressSlider; /** * 声明播放视频的控件属性[既可以播放视频也可以播放音频] */ @property (nonatomic,strong)AVPlayer *player; /** * 播放的总时长 */ @property (nonatomic,assign)CGFloat sumPlayOperation; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //设置播放的url NSString *playString = @"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4"; NSURL *url = [NSURL URLWithString:playString]; //设置播放的项目 AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url]; //初始化player对象 self.player = [[AVPlayer alloc] initWithPlayerItem:item]; //设置播放页面 AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:_player]; //设置播放页面的大小 layer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 300); layer.backgroundColor = [UIColor cyanColor].CGColor; //设置播放窗口和当前视图之间的比例显示内容 layer.videoGravity = AVLayerVideoGravityResizeAspect; //添加播放视图到self.view [self.view.layer addSublayer:layer]; //设置播放进度的默认值 self.progressSlider.value = 0; //设置播放的默认音量值 self.player.volume = 1.0f; } #pragma mark - 开始按钮响应方法 - (IBAction)startPlayer:(id)sender { [self.player play]; } #pragma mark - 暂停按钮响应方法 - (IBAction)stopPlayer:(id)sender { [self.player pause]; } #pragma mark - 改变进度 - (IBAction)changeProgress:(id)sender { self.sumPlayOperation = self.player.currentItem.duration.value/self.player.currentItem.duration.timescale; //CMTimeMake(a,b) a表示当前时间,b表示每秒钟有多少帧 [self.player seekToTime:CMTimeMakeWithSeconds(self.progressSlider.value*self.sumPlayOperation, self.player.currentItem.duration.timescale) completionHandler:^(BOOL finished) { [self.player play]; }]; }
时间: 2024-10-14 00:50:40