几种播放视频文件的方式(四) —— 基于AVKit框架的视频播放(一)

版本记录

版本号 时间
V1.0 2017.12.30

前言

iOS系统中有很多方式可以播放视频文件,这里我们就详细的说明下播放视频文件的原理和实例。希望能帮助到大家,大家能喜欢。感兴趣的可以参考上面几篇。
1. 几种播放视频文件的方式(一) —— 总结播放视频的几种方式(一)
2. 几种播放视频文件的方式(二) —— 基于MediaPlayer框架的视频播放(一)
3. 几种播放视频文件的方式(三) —— 基于AVFoundation框架视频播放(一)

AVKit框架

1. 框架API

我们还是先看一下AVKit的API

/*
    File:  AVKit.h
    
    Framework:  AVKit
    
    Copyright © 2013-2016 Apple Inc. All rights reserved.
    
    To report bugs, go to:  http://developer.apple.com/bugreporter/
    
 */

#import <AVKit/AVKitDefines.h>

#if TARGET_OS_IPHONE
#import <AVKit/AVError.h>
#import <AVKit/AVPictureInPictureController.h>
#import <AVKit/AVPlayerViewController.h>
#import <AVKit/AVRoutePickerView.h>
#else
#import <AVKit/AVCaptureView.h>
#import <AVKit/AVPlayerView.h>
#endif // TARGET_OS_IPHONE

2. AVPlayerViewController

下面我们看一下该类的API

/*
    File:  AVPlayerViewController.h
    
    Framework:  AVKit
    
    Copyright © 2014-2017 Apple Inc. All rights reserved.
    
 */

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

NS_ASSUME_NONNULL_BEGIN

@protocol AVPlayerViewControllerDelegate;

/*!
    @class      AVPlayerViewController
    @abstract   AVPlayerViewController is a subclass of UIViewController that can be used to display the visual content of an AVPlayer object and the standard playback controls.
 */

API_AVAILABLE(ios(8.0))
@interface AVPlayerViewController : UIViewController

/*!
    @property   player
    @abstract   The player from which to source the media content for the view controller.
 */
@property (nonatomic, strong, nullable) AVPlayer *player;

/*!
    @property   showsPlaybackControls
    @abstract   Whether or not the receiver shows playback controls. Default is YES.
    @discussion Clients can set this property to NO when they don't want to have any playback controls on top of the visual content (e.g. for a game splash screen).
 */
@property (nonatomic) BOOL showsPlaybackControls;

/*!
    @property   videoGravity
    @abstract   A string defining how the video is displayed within an AVPlayerLayer bounds rect.
    @discussion Options are AVLayerVideoGravityResizeAspect, AVLayerVideoGravityResizeAspectFill and AVLayerVideoGravityResize. AVLayerVideoGravityResizeAspect is default.
                See <AVFoundation/AVAnimation.h> for a description of these options.
 */
@property (nonatomic, copy) NSString *videoGravity;

/*!
    @property   readyForDisplay
    @abstract   Boolean indicating that the first video frame has been made ready for display for the current item of the associated AVPlayer.
 */
@property (nonatomic, readonly, getter = isReadyForDisplay) BOOL readyForDisplay;

/*!
    @property   videoBounds
    @abstract   The current size and position of the video image as displayed within the receiver's view's bounds.
 */
@property (nonatomic, readonly) CGRect videoBounds;

/*!
    @property   contentOverlayView
    @abstract   Use the content overlay view to add additional custom views between the video content and the controls.
 */
@property (nonatomic, readonly, nullable) UIView *contentOverlayView;

/*!
    @property   allowsPictureInPicturePlayback
    @abstract   Whether or not the receiver allows Picture in Picture playback. Default is YES.
 */
@property (nonatomic) BOOL allowsPictureInPicturePlayback API_AVAILABLE(ios(9.0));

/*!
    @property   updatesNowPlayingInfoCenter
    @abstract   Whether or not the now playing info center should be updated. Default is YES.
 */
@property (nonatomic) BOOL updatesNowPlayingInfoCenter API_AVAILABLE(ios(10.0));

/*!
    @property   entersFullScreenWhenPlaybackBegins
    @abstract   Whether or not the receiver automatically enters full screen when the play button is tapped. Default is NO.
    @discussion If YES, the receiver will show a user interface tailored to this behavior.
 */
@property (nonatomic) BOOL entersFullScreenWhenPlaybackBegins API_AVAILABLE(ios(11.0));

/*!
    @property   exitsFullScreenWhenPlaybackEnds
    @abstract   Whether or not the receiver automatically exits full screen when playback ends. Default is NO.
    @discussion If multiple player items have been enqueued, the receiver exits fullscreen once no more items are remaining in the queue.
 */
@property (nonatomic) BOOL exitsFullScreenWhenPlaybackEnds API_AVAILABLE(ios(11.0));

/*!
    @property   delegate
    @abstract   The receiver's delegate.
 */
@property (nonatomic, weak, nullable) id <AVPlayerViewControllerDelegate> delegate API_AVAILABLE(ios(9.0));

@end


/*!
    @protocol   AVPlayerViewControllerDelegate
    @abstract   A protocol for delegates of AVPlayerViewController.
 */

@protocol AVPlayerViewControllerDelegate <NSObject>
@optional

/*!
    @method     playerViewControllerWillStartPictureInPicture:
    @param      playerViewController
                The player view controller.
    @abstract   Delegate can implement this method to be notified when Picture in Picture will start.
 */
- (void)playerViewControllerWillStartPictureInPicture:(AVPlayerViewController *)playerViewController;

/*!
    @method     playerViewControllerDidStartPictureInPicture:
    @param      playerViewController
                The player view controller.
    @abstract   Delegate can implement this method to be notified when Picture in Picture did start.
 */
- (void)playerViewControllerDidStartPictureInPicture:(AVPlayerViewController *)playerViewController;

/*!
    @method     playerViewController:failedToStartPictureInPictureWithError:
    @param      playerViewController
                The player view controller.
    @param      error
                An error describing why it failed.
    @abstract   Delegate can implement this method to be notified when Picture in Picture failed to start.
 */
- (void)playerViewController:(AVPlayerViewController *)playerViewController failedToStartPictureInPictureWithError:(NSError *)error;

/*!
    @method     playerViewControllerWillStopPictureInPicture:
    @param      playerViewController
                The player view controller.
    @abstract   Delegate can implement this method to be notified when Picture in Picture will stop.
 */
- (void)playerViewControllerWillStopPictureInPicture:(AVPlayerViewController *)playerViewController;

/*!
    @method     playerViewControllerDidStopPictureInPicture:
    @param      playerViewController
                The player view controller.
    @abstract   Delegate can implement this method to be notified when Picture in Picture did stop.
 */
- (void)playerViewControllerDidStopPictureInPicture:(AVPlayerViewController *)playerViewController;

/*!
    @method     playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart:
    @param      playerViewController
                The player view controller.
    @abstract   Delegate can implement this method and return NO to prevent player view controller from automatically being dismissed when Picture in Picture starts.
 */
- (BOOL)playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart:(AVPlayerViewController *)playerViewController;

/*!
    @method     playerViewController:restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:
    @param      playerViewController
                The player view controller.
    @param      completionHandler
                The completion handler the delegate needs to call after restore.
    @abstract   Delegate can implement this method to restore the user interface before Picture in Picture stops.
 */
- (void)playerViewController:(AVPlayerViewController *)playerViewController restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:(void (^)(BOOL restored))completionHandler;

@end

NS_ASSUME_NONNULL_END

功能实现

下面我们看一下功能实现。

#import "ViewController.h"
#import <AVKit/AVKit.h>

@interface ViewController () <AVPlayerViewControllerDelegate>

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerViewController *playerVC;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //如果没有声音,需要加上这一句话
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    AVPlayer *player = [AVPlayer playerWithURL:[[NSBundle mainBundle] URLForResource:@"movie.mp4" withExtension:nil]];
    self.player = player;
    
    AVPlayerViewController *playerVC = [[AVPlayerViewController alloc] init];
    self.playerVC = playerVC;
    playerVC.player = player;
    playerVC.view.frame = self.view.frame;
    playerVC.delegate = self;
    // 设置拉伸模式
    playerVC.videoGravity = AVLayerVideoGravityResizeAspect;
    // 设置是否显示媒体播放组件
    playerVC.showsPlaybackControls = YES;
    [self.view addSubview:playerVC.view];
    [self addChildViewController:playerVC];
    
    //这个属性和图片填充视图的属性类似,也可以设置为自适应试图大小。
    player.externalPlaybackVideoGravity = AVLayerVideoGravityResizeAspectFill;
    
    [player play];
}

#pragma mark - AVPlayerViewControllerDelegate

- (void)playerViewControllerDidStartPictureInPicture:(AVPlayerViewController *)playerViewController
{
    NSLog(@"视频已经开始的时候调用");
}

- (void)playerViewController:(AVPlayerViewController *)playerViewController failedToStartPictureInPictureWithError:(NSError *)error
{
    NSLog(@"播放失败的时候");
}

- (void)playerViewControllerWillStopPictureInPicture:(AVPlayerViewController *)playerViewController
{
    NSLog(@"将要停止的时候");
}

- (void)playerViewControllerDidStopPictureInPicture:(AVPlayerViewController *)playerViewController
{
    NSLog(@"已经停止的时候");
}

@end

下面看一下实现效果

后记

未完,待续~~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,923评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,154评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,775评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,960评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,976评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,972评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,893评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,709评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,159评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,400评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,552评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,265评论 5 341
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,876评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,528评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,701评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,552评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,451评论 2 352

推荐阅读更多精彩内容