iOS背景播放视频

之前看过很多app的登录页面,会有背景在循环播放一段视频,觉得非常酷炫。
然后自己研究了许久,终于弄出点样子,跟大家分享一下。
(gif图做的很烂)


beijingVideo.2018-09-26 15_52_32.gif

1.创建父类视图控制器

这是.h文件

#import 

//视频播放时的窗口属性enum
enum ScalingMode {
  resize,
  resizeAspect,
  resizeAspectFill  //默认推荐这个属性 
};

@interface FKCVideoViewController : UIViewController

@property (nonatomic,strong) NSURL * contentURL ; //视频文件地址
@property (nonatomic,assign) CGRect videoFrame ; //播放器的frame
@property (nonatomic,assign) CGFloat startTime ; //视频开始时间
@property (nonatomic,assign) CGFloat duration ; //循环时间 不写的话就默认是视频总长度
@property (nonatomic,strong) UIColor * backgroundColor ; //播放器背景颜色
@property (nonatomic,assign) BOOL sound ; //是否开启声音
@property (nonatomic,assign) CGFloat alpha ; //透明度
@property (nonatomic,assign) BOOL alwaysRepeat ; //是否一致循环
@property (nonatomic,assign) enum ScalingMode fillMode ; //视频播放时的窗口属性

@end

然后再到.m文件里来
头文件一定要导入哦~

#import 
#import 

@interface FKCVideoViewController ()

@property (nonatomic,strong) AVPlayerViewController * moviePlayer ; //播放控制器本体啦 
@property (nonatomic,assign) CGFloat moviePlayerSoundLevel ;  //控制音量的(有点冗余)

@end

实现一些刚才定义的属性的set方法

-(void)setBackgroundColor:(UIColor *)backgroundColor
{
    self.view.backgroundColor = backgroundColor ;
}

-(void)setSound:(BOOL)sound
{
    if (sound) {
        self.moviePlayerSoundLevel = 1.0 ;
    }
    else
    {
        self.moviePlayerSoundLevel = 0.0 ;
    }
}

-(void)setAlpha:(CGFloat)alpha
{
    self.moviePlayer.view.alpha = alpha ;
}    

-(void)setAlwaysRepeat:(BOOL)alwaysRepeat
{
    if (alwaysRepeat) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:self.moviePlayer.player.currentItem] ;
    }
}

-(void)setFillMode:(enum ScalingMode)fillMode
{
    switch (fillMode) {
        case resize:
            self.moviePlayer.videoGravity = AVLayerVideoGravityResize ;
            break;
        case resizeAspect:
            self.moviePlayer.videoGravity = AVLayerVideoGravityResizeAspect ;
            break;
        case resizeAspectFill:
            self.moviePlayer.videoGravity = AVLayerVideoGravityResizeAspectFill ;
            break;
        default:
            self.moviePlayer.videoGravity = AVLayerVideoGravityResizeAspectFill ;
            break;
    }
}

//对应 setAlwaysRepeat 的监听
-(void)playerItemDidReachEnd
{
    [self.moviePlayer.player seekToTime:kCMTimeZero] ;
    [self.moviePlayer.player play] ;
}

然后最重要的一步来了

-(void)setContentURL:(NSURL *)contentURL
{
    self.moviePlayer = [[AVPlayerViewController alloc]init] ; //这个刚开始没写 一直没有视图,但是不一定放在这里是最好的。
    [self setFKCMoviePlayer:contentURL] ; //在填写视频地址时,完成播放器的设置。
}

为了不堵塞主线程,这里用到了GCD多线程

-(void)setFKCMoviePlayer:(NSURL *)url
{
    VideoCutter * videoCutter = [VideoCutter new] ; //这是一个对视频进行一次处理的类,等下上代码
    [videoCutter cropVideoWithUrl:url andStartTime:self.startTime andDuration:self.duration andCompletion:^(NSURL *videoPath, NSError *error) {
    
        if ([videoPath isKindOfClass: [NSURL class]]) {
        
            dispatch_queue_t globalDispatchQueueDefault = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                    
            dispatch_async(globalDispatchQueueDefault, ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.moviePlayer.player = [[AVPlayer alloc] initWithURL:videoPath] ;
                    [self.moviePlayer.player play] ;
                    self.moviePlayer.player.volume = self.moviePlayerSoundLevel ;
                });
            }) ;
        }
    }] ;
}

然后是两个生命周期的方法

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated] ;
    self.moviePlayer.view.frame = self.videoFrame ;
    self.moviePlayer.showsPlaybackControls = false ;
    [self.view addSubview:self.moviePlayer.view] ;
    [self.view sendSubviewToBack:self.moviePlayer.view] ;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated] ;
    [[NSNotificationCenter defaultCenter] removeObserver:self] ;
}

viewDidLoad里面啥都没写哦

然后再回到刚才说的那个类VideoCutter
2.视频处理类VideoCutter
这里是.h文件

#import 
#import 
#import 

@interface VideoCutter : NSObject

-(void)cropVideoWithUrl:(NSURL *)url andStartTime:(CGFloat)startTime andDuration:(CGFloat)duration andCompletion:(void(^)(NSURL * videoPath,NSError * error))task ;

@end

再来到.m文件里
好像总共也就这一个方法。。。

-(void)cropVideoWithUrl:(NSURL *)url andStartTime:(CGFloat)startTime andDuration:(CGFloat)duration andCompletion:(void(^)(NSURL * videoPath,NSError * error))task{

    dispatch_queue_t globalDispatchQueueDefault = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//由于本人也是参考其他大神的作品发挥的,所以可能理解的不是很准确。    

    dispatch_async(globalDispatchQueueDefault, ^{
        AVURLAsset * asset = [[AVURLAsset alloc] initWithURL:url options:nil] ;
        AVAssetExportSession * exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:@"AVAssetExportPresetHighestQuality"] ;
//这里是得到一个视频转码类AVAssetExportSession 然后质量是最高
        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true) ;
        NSString * outputURL = paths.firstObject ;
        NSFileManager * manager = [NSFileManager defaultManager] ;
    
        [manager createDirectoryAtPath:outputURL withIntermediateDirectories:true attributes:nil error:nil] ;
    
        outputURL = [outputURL stringByAppendingPathComponent:@"output.mp4"] ;
        //拿到转码后的视频地址

        [manager removeItemAtPath:outputURL error:nil] ;
    
        if ([exportSession isKindOfClass:[AVAssetExportSession class]]) {
            exportSession.outputURL = [[NSURL alloc] initFileURLWithPath:outputURL] ;
            exportSession.shouldOptimizeForNetworkUse = true ;
            exportSession.outputFileType = AVFileTypeMPEG4 ;
            Float64 duration64 = duration ;
            Float64 startTime64 = startTime ;
            CMTime start = CMTimeMakeWithSeconds(startTime64, 600) ;
            CMTime duration = CMTimeMakeWithSeconds(duration64, 600) ;
            CMTimeRange range = CMTimeRangeMake(start, duration) ;
            exportSession.timeRange = range ;
        
            [exportSession exportAsynchronouslyWithCompletionHandler:^{
                switch (exportSession.status) {
                    case AVAssetExportSessionStatusCompleted:
                        task(exportSession.outputURL,nil) ;
                      //转换ok后把视频地址block回去
                        break;
                    case AVAssetExportSessionStatusFailed:
                        NSLog(@"%@",exportSession.error) ;
                        break;
                    case AVAssetExportSessionStatusCancelled:
                        NSLog(@"%@",exportSession.error) ;
                        break;
                    default:
                        NSLog(@"default case") ;
                        break;
                }
            }] ;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
        //回到主线程
        });
    }) ;
}

现在整个视频播放器已经写好了,调用!

在viewController.h里面
一定要继承刚才写的播放器

#import 
#import "FKCVideoViewController.h"

@interface ViewController:FKCVideoViewController


@end

然后回到.m文件里

    NSString * videoPath = [[NSBundle mainBundle] pathForResource:@"spotify" ofType:@"mp4"] ;
//视频地址
    NSURL * videoUrl = [[NSURL alloc] initFileURLWithPath:videoPath] ;
    self.videoFrame = self.view.frame ; //设置播放器的frame
    self.fillMode = resizeAspectFill ; //设置播放器填充属性
    self.alwaysRepeat = true ; //是否一致循环
    self.sound = false ; //是否有音效
    self.startTime = 2.0 ; //开始时间
    self.alpha = 0.8 ; //透明度

    self.contentURL = videoUrl ; //把地址给到播放器,顺带也设置了
    self.view.userInteractionEnabled = NO ; //关闭用户交互

OK大功告成!

小白不会写文章,有遗漏的地方欢迎指出。

你可能感兴趣的:(iOS背景播放视频)