VideoHelperViewController.m 13.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
//
//  VideoHelperViewController.m
//  Lighting
//
//  Created by 曹云霄 on 2016/11/25.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "VideoHelperViewController.h"

曹云霄's avatar
曹云霄 committed
11
@interface VideoHelperViewController ()<UIDocumentInteractionControllerDelegate>
12 13 14 15 16
{
    UISlider* volumeViewSlider;//保存需要改变的量
    float systemVolume;//系统音量值
    CGPoint startPoint;//起始位置
}
17

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

/**
 导航栏、工具类是否隐藏
 */
@property (nonatomic,assign) BOOL toolNaviViewIsHide;

@end

@implementation VideoHelperViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self uiConfigAction];
}

#pragma mark - UI
- (void)uiConfigAction
{
    self.videoNavigationView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    self.videoToolView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideOrShowNavigationBarAndToolBar)]];
40 41 42 43 44 45 46 47 48 49 50
    
    //获取系统音量
    MPVolumeView *volumeView = [[MPVolumeView alloc] init];
    volumeViewSlider = nil;
    for (UIView *view in [volumeView subviews]){
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
            volumeViewSlider = (UISlider *)view;
            break;
        }
    }
    systemVolume = volumeViewSlider.value;
51 52
}

曹云霄's avatar
曹云霄 committed
53

54 55 56 57 58 59 60 61 62 63 64 65
#pragma mark - 播放地址
- (void)setLearningItem:(CustomStudyEntity *)learningItem
{
    _learningItem = learningItem;
    [self resetPlayer];
    if (_learningItem) {
        [self setUpAVPlayer];
        [self addAVPlayerKVO];
        [self addProgressObserver];
    }
}

66

67 68 69
#pragma mark - SetUp AVPlayer
- (void)setUpAVPlayer
{
70 71
    VIResourceLoaderManager *resourceLoaderManager = [VIResourceLoaderManager new];
    self.resourceLoaderManager = resourceLoaderManager;
72 73
    self.playerItem = [resourceLoaderManager playerItemWithURL:[NSURL URLWithString:self.learningItem.attachment.fileUrl]];
    VICacheConfiguration *configuration = [VICacheManager cacheConfigurationForURL:[NSURL URLWithString:self.learningItem.attachment.fileUrl]];
74 75 76
    if (configuration.progress >= 1.0) {
        NSLog(@"缓存完成");
    }
77
    [XBLoadingView showHUDViewWithDefaultWithView:self.view];
78 79
    self.customPlayer = [[AVPlayer alloc] initWithPlayerItem:self.playerItem];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.customPlayer];
80 81
    self.playerLayer.frame = CGRectMake(0, 0, ScreenWidth*2/3, ScreenHeight/2);
    [self.view.layer insertSublayer:self.playerLayer atIndex:0];
82
    self.videoTitleLabel.text = self.learningItem.title;
83 84 85 86 87 88 89 90 91 92
}

#pragma mark - AVPlayer KVO
- (void)addAVPlayerKVO
{
    //播放状态属性
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //监控网络加载情况属性
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    //给AVPlayerItem添加播放完成通知
93
    [Notification addObserver:self selector:@selector(playFinish) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
94 95 96 97
}

#pragma mark -KVO回调
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
98
    WS(weakSelf);
99 100 101 102
    if ([keyPath isEqualToString:@"status"]) {//播放状态
        NSInteger status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
        switch (status) {
            case AVPlayerStatusFailed:
103 104
                self.bufferProgressView.progress = ZERO;
                self.playButton.selected = YES;
105
                [XBLoadingView hideHUDViewWithDefaultWithView:self.view];
106
                [XBLoadingView showHUDViewWithText:@"播放失败"];
107 108
                break;
            case AVPlayerStatusReadyToPlay://正在播放
109 110
            {
                self.playButton.selected = NO;
111
                [XBLoadingView hideHUDViewWithDefaultWithView:self.view];
112
                self.playItemTotalTimeLabel.text = [NSString stringWithFormat:@"/ %@",[self convertTime:CMTimeGetSeconds(self.playerItem.duration)]];
113 114 115
                NSInteger second = [self.learningItem.attachment.playTime integerValue];
                NSString *timeString = [self timeFormatted:second];
                if (![[self class] isBlankString:timeString] && second < (NSInteger)CMTimeGetSeconds(self.playerItem.duration)) {
116
                    [self stopPlay];
曹云霄's avatar
曹云霄 committed
117
                    ShowDefaultAlertView(self, nil, [NSString stringWithFormat:@"上次播放时间:%@,是否继续播放",timeString], UIAlertControllerStyleAlert, ^{
118
                        [weakSelf.customPlayer seekToTime:CMTimeMake([weakSelf.learningItem.attachment.playTime integerValue], ONE) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
119
                        [weakSelf startPlay];
120
                    }, ^{
121
                        [weakSelf startPlay];
122
                    });
123
                }
124
                break;
125
            }
126 127 128 129 130
            default:
                break;
        }
    }else if ([keyPath isEqualToString:@"loadedTimeRanges"]){//缓冲
        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
131
        if (timeInterval > self.getCurrentPlayingTime+5 && !self.playButton.selected){ // 缓存 大于 播放 当前时长+5
132 133 134 135 136
            [self.customPlayer play];
        }
    }
}

137

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
#pragma mark - 返回当前视频播放时长
- (double)getCurrentPlayingTime{
    return self.customPlayer.currentTime.value/self.customPlayer.currentTime.timescale;
}

#pragma mark - 返回当前视频缓存时长
- (NSTimeInterval)availableDuration{
    NSArray *loadedTimeRanges = [[self.customPlayer currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}

#pragma mark -播放进度条更新
-(void)addProgressObserver {
    
    WS(weakSelf);
    AVPlayerItem *playerItem = self.customPlayer.currentItem;
    self.avplayerServer = [self.customPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time){
        float current = CMTimeGetSeconds(time);
        float total = CMTimeGetSeconds(playerItem.duration);
        //更新进度条
        float progress = current/total;
        weakSelf.bufferProgressView.progress = progress;
        //更新播放时间
        CMTime ctime = weakSelf.customPlayer.currentTime;
        weakSelf.playingTimeLabel.text = [weakSelf convertTime:ctime.value/ctime.timescale];
167
        //更新播放百分比
168 169
        if (progress) {
            if ([weakSelf.progressDelegate respondsToSelector:@selector(videoPlayProportion:withIndexPath:)]) {
170
                [weakSelf.progressDelegate videoPlayProportion:progress*100 withIndexPath:weakSelf.indexPath];
171
            }
172
        }
173 174 175 176 177 178 179
    }];
}

#pragma mark - 隐藏(显示)状态栏、工具栏
- (void)hideOrShowNavigationBarAndToolBar
{
    [UIView animateWithDuration:0.4 animations:^{
180 181
        self.videoNavigationView.alpha = self.toolNaviViewIsHide?1:0;
        self.videoToolView.alpha = self.toolNaviViewIsHide?1:0;
182 183
        
    }completion:^(BOOL finished) {
184 185 186 187 188 189
        self.toolNaviViewIsHide = !self.toolNaviViewIsHide;
        if (!self.toolNaviViewIsHide) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self hideOrShowNavigationBarAndToolBar];
            });
        }
190 191 192 193
    }];
}

#pragma mark -计算时间
194
- (NSString *)convertTime:(NSInteger)interval
195
{
196 197 198 199 200 201 202 203 204 205 206 207
    NSUInteger secondPerDay = 24 * 60 * 60;
    NSUInteger secondPerHour = 60 * 60;
    NSUInteger secondPerMinute = 60;
    // 剩余小时不应该大于24小时,所以应该先除去满足一天的秒数,再计算还剩下多少小时
    NSInteger hour = interval % secondPerDay / secondPerHour;
    // 剩余分钟数与上面同理
    NSInteger minute = interval % secondPerHour / secondPerMinute;
    // 剩余秒数直接等于秒数对每分钟秒数所取的余数
    NSInteger second = interval % secondPerMinute;
    NSMutableString *string = [NSMutableString string];
    if (hour) {
        [string appendString:[NSString stringWithFormat:@"%02zd:",hour]];
208
    }
209 210
    [string appendString:[NSString stringWithFormat:@"%02zd:%02zd",minute,second]];
    return string;
211 212 213 214 215
}

#pragma mark - 播放完成
- (void)playFinish
{
216
    [self.customPlayer seekToTime:kCMTimeZero];
217
    self.playButton.selected = YES;
218 219 220
    if ([self.delegate respondsToSelector:@selector(videoPlayFinish:withIndexPath:)]) {
        [self.delegate videoPlayFinish:self.learningItem withIndexPath:self.indexPath];
    } 
221 222 223 224
}

#pragma mark - 播放、暂停
- (IBAction)playOrPauseButtonClickAction:(UIButton *)sender {
225 226 227 228 229 230 231 232 233 234
   
    if (sender.selected && !self.learningItem) {
        if ([self.delegate respondsToSelector:@selector(isFirstPLayOrPPTPlay:)]) {
            if (!self.indexPath) {
                self.indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            }
            [self.delegate isFirstPLayOrPPTPlay:self.indexPath];
        }
        return;
    }
235 236
    sender.selected = !sender.selected;
    if (sender.selected) {
237
        [self stopPlay];
238
    }else {
239
        [self startPlay];
240 241 242
    }
}

243 244 245 246 247 248 249 250 251 252 253 254 255 256
#pragma mark - 播放
- (void)startPlay
{
    self.playButton.selected = NO;
    [self.customPlayer play];
}

#pragma mark - 暂停
- (void)stopPlay
{
    self.playButton.selected = YES;
    [self.customPlayer pause];
}

257 258
#pragma mark - 退出播放
- (IBAction)exitPlayControllerButtonClick:(UIButton *)sender {
259

260 261
    if (self.playerLayer.frame.size.height == ScreenHeight) {
        if (self.zoomButtonClickBlock) {
262
            self.zoomButton.selected = NO;
263 264 265 266 267
            self.zoomButtonClickBlock(NO);
        }
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
268 269 270 271 272
}

#pragma mark - 后退5秒
- (IBAction)backFiveSecondButtnClick:(UIButton *)sender {
    
273
    [self stopPlay];
274
    [self.customPlayer seekToTime:CMTimeMake([self getCurrentPlayingTime]-5, 1) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
275 276 277 278 279
}

#pragma mark - 放大缩小按钮
- (IBAction)zoomButtonClick:(UIButton *)sender {
    
280 281 282
    if (!self.learningItem) {
        [XBLoadingView showHUDViewWithText:@"请先选择学习项"];return;
    }
283 284 285 286 287 288
    sender.selected = !sender.selected;
    if (self.zoomButtonClickBlock) {
        self.zoomButtonClickBlock(sender.selected);
    }
}

289 290 291
#pragma mark - 页面消失后释放播放器
- (void)viewDidDisappear:(BOOL)animated
{
292
    [super viewDidDisappear:animated];
293 294 295 296 297
    [self.customPlayer pause];
    [self.customPlayer.currentItem cancelPendingSeeks];
    [self.customPlayer.currentItem.asset cancelLoading];
}

298 299 300
#pragma mark - 重置播放器
- (void)resetPlayer
{
301
    [self stopPlay];
302
    [self.customPlayer seekToTime:kCMTimeZero];
303
    [self customDealloc];
304 305 306 307
    self.bufferProgressView.progress = ZERO;
    self.playingTimeLabel.text = @"00:00";
    self.playItemTotalTimeLabel.text = @"/ 00:00";
    self.videoTitleLabel.text = nil;
曹云霄's avatar
曹云霄 committed
308
    [self.playerLayer removeFromSuperlayer];
309 310
}

311
#pragma mark - 释放KVO
312
- (void)customDealloc
313
{
314 315 316 317 318
    //避免多次释放崩溃
    @try {
        [self.playerItem removeObserver:self forKeyPath:@"status"];
        [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
        [self.customPlayer removeTimeObserver:self.avplayerServer];
319
        [Notification removeObserver:self];
320
    } @catch (NSException *exception) {
321
        NSLog(@"多次释放");
322
    }
323 324
}

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383

#pragma mark -开始滑动时
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    if(event.allTouches.count == 1){
        //保存当前触摸的位置
        CGPoint point = [[touches anyObject] locationInView:self.view];
        startPoint = point;
    }
}

#pragma mark -手势滑动的距离
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    
    if(event.allTouches.count == 1){
        //计算位移
        CGPoint point = [[touches anyObject] locationInView:self.view];
        float dy = point.y - startPoint.y;
        int index = (int)dy;
        //20是因为排除横向滑动时的偏差
        if(index > 20){
            if(index%5==0){//每10个像素声音减一格
                if(systemVolume > 0.1){
                    systemVolume = systemVolume-0.05;
                    [volumeViewSlider setValue:systemVolume animated:YES];
                    [volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
                }
            }
        }else if (index < -20){
            if(index%5==0){//每10个像素声音增加一格
                if(systemVolume>=0 && systemVolume<1){
                    systemVolume = systemVolume+0.05;
                    [volumeViewSlider setValue:systemVolume animated:YES];
                    [volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
                }
            }
        }
        //音量调节
        [self volumeSet:volumeViewSlider];
    }
}

#pragma mark -调节音量
- (void)volumeSet:(UISlider *)slider
{
    NSArray *audioTracks = [self.playerItem.asset tracksWithMediaType:AVMediaTypeAudio];
    NSMutableArray *allAudioParams = [NSMutableArray array];
    for (AVAssetTrack *track in audioTracks) {
        
        AVMutableAudioMixInputParameters *audioInputParams =
        [AVMutableAudioMixInputParameters audioMixInputParameters];
        [audioInputParams setVolume:slider.value atTime:kCMTimeZero];
        [audioInputParams setTrackID:[track trackID]];
        [allAudioParams addObject:audioInputParams];
    }
    AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
    [audioMix setInputParameters:allAudioParams];
    [self.playerItem setAudioMix:audioMix];
}

384 385 386 387
- (void)dealloc
{
    [self customDealloc];
}
388 389

@end