iOS - 视频和音频相关

2016-10-31  本文已影响0人  Mn_Su

注:本文采用了第三方框架 Masonry 和 ReactiveCocoa,请自行导入

相关素材

Paste_Image.png

第一.视频

    1.导入头文件和定义属性

            #import <MediaPlayer/MediaPlayer.h>
            @property (nonatomic,strong) MPMoviePlayerController *moviePlayer;//视频播放控制器

    2.在 viewDidLoad 方法里面添加 play 方法和通知

            //添加通知
            [self addNotification];

    3.相关方法
          
            -(void)dealloc{
                //移除所有通知监控
                [[NSNotificationCenter defaultCenter] removeObserver:self];
            }
            
            #pragma mark - 私有方法
            /**
             *  取得本地文件路径
             *
             *  @return 文件路径
             */
            -(NSURL *)getFileUrl{
                NSString *urlStr=[[NSBundle mainBundle] pathForResource:@"经济技术.mp4" ofType:nil];
                NSURL *url=[NSURL fileURLWithPath:urlStr];
                return url;
            }
            
            
            /**
             *  取得网络文件路径
             *
             *  @return 文件路径
             */
            -(NSURL *)getNetworkUrl{
                NSString *urlStr=@"http://v.qq.com/x/cover/954n4p1nqozp5bg.html";
                urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                NSURL *url=[NSURL URLWithString:urlStr];
                return url;
            }
            
            /**
             *  创建媒体播放控制器
             *
             *  @return 媒体播放控制器
             */
            -(MPMoviePlayerController *)moviePlayer{
                if (!_moviePlayer) {
                    NSURL *url=[self getFileUrl];
                    _moviePlayer=[[MPMoviePlayerController alloc]initWithContentURL:url];
                    _moviePlayer.view.frame = CGRectMake(0, 65, WIDTH, (HEIGHT-65-46)/3);
                    _moviePlayer.view.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
                    [self.view addSubview:_moviePlayer.view];  

                    //覆盖播放器表面背景
                    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 65, WIDTH, (HEIGHT-65-46)/3)];
                    myView.backgroundColor = [UIColor clearColor];
                    [self.view addSubview:myView];
                    
                    //播放点击按钮
                    UIButton *playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                    [playBtn setImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
                    [myView addSubview:playBtn];
                    [playBtn makeConstraints:^(MASConstraintMaker *make) {
                        make.top.equalTo(myView.top).offset((HEIGHT-65-46)/3*0.5-20);
                        make.left.equalTo(self.view.left).offset(WIDTH/2-20);
                        make.width.equalTo(40);
                        make.height.equalTo(40);
                    }];
                    [[playBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
                        [myView removeFromSuperview];
                        [self.moviePlayer play];
                    }];
                  
                }
                return _moviePlayer;
            }
            
            /**
             *  获取视频缩略图
             */
            -(void)thumbnailImageRequest{
                //获取13.0s、21.5s的缩略图
                [self.moviePlayer requestThumbnailImagesAtTimes:@[@13.0,@21.5] timeOption:MPMovieTimeOptionNearestKeyFrame];
            }

第二.音频

    1.导入头文件和定义属性

            #import <AVFoundation/AVFoundation.h>
            //音频相关
            @property (nonatomic,strong) AVAudioPlayer *audioPlayer;//播放器
            @property (nonatomic,strong)  UILabel *controlPanel; //控制面板
            @property (nonatomic,strong)  UIProgressView *playProgress;//播放进度
            @property (nonatomic,strong) UIView *playBG;
            @property (nonatomic,strong)  UIButton *playOrPause; //播放/暂停按钮(如果tag为0认为是暂停状态,1是播放状态)
            @property (nonatomic,strong) NSTimer *timer;//进度更新定时器
            @property (nonatomic,strong) UILabel *havTime;
            @property (nonatomic,strong) UILabel *totalTime;

       2.相关申明

//==============================分割线分割线=============*=================

            //播放视图
            self.playBG = [[UIView alloc] init];
            [self.view addSubview:self.playBG];
            [self.playBG makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(pop.picLab.bottom).offset(60);
                make.left.equalTo(self.view.left).offset(60);
                make.width.equalTo(WIDTH-120);
                make.height.equalTo(80);
            }];
            
            self.playOrPause = [UIButton buttonWithType:UIButtonTypeCustom];
            [self.playOrPause setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
            [self.playOrPause setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateSelected];
            self.playOrPause.layer.cornerRadius = 25;
            self.playOrPause.layer.shouldRasterize = YES;
            self.playOrPause.layer.rasterizationScale = [UIScreen mainScreen].scale;
            [self.playBG addSubview:self.playOrPause];
            [self.playOrPause makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.playBG.top).offset(15);
                make.left.equalTo(self.playBG.left).offset(10);
                make.width.equalTo(50);
                make.height.equalTo(50);
            }];         
          [[self.playOrPause rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
                self.playOrPause.selected = !self.playOrPause.selected;
                if (self.playOrPause.selected) {
                    [self play];
                }else{
                    [self pause];
                }
           }];
            
            self.playProgress = [[UIProgressView alloc] init];
            [self.playProgress setProgressViewStyle:UIProgressViewStyleDefault];
            self.playProgress.progressTintColor = WHITECOLOR;
            self.playProgress.trackTintColor = [UIColor colorWithRed:120/255.0 green:53/255.0 blue:54/255.0 alpha:1];
            [self.playBG addSubview:self.playProgress];
            [self.playProgress makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.playBG.top).offset(37.5);
                make.left.equalTo(self.playOrPause.right).offset(5);
                make.width.equalTo(WIDTH-120-75);
                make.height.equalTo(5);
            }];
           
            self.havTime = [[UILabel alloc] init];
            self.havTime.text = @"00:00";
            self.havTime.textAlignment = NSTextAlignmentLeft;
            self.havTime.font = [UIFont systemFontOfSize:12];
            self.havTime.textColor = WHITECOLOR;
            [self.playBG addSubview:self.havTime];
            [self.havTime makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.playProgress.bottom).offset(0);
                make.left.equalTo(self.playOrPause.right).offset(5);
                make.width.equalTo(100);
                make.height.equalTo(20);
            }];
            
            self.totalTime = [[UILabel alloc] init];
            NSInteger totalTime = self.audioPlayer.duration;
            self.totalTime.text = [NSString stringWithFormat:@"%02ld:%02ld",totalTime/60,totalTime/60];
            self.totalTime.textAlignment = NSTextAlignmentRight;
            self.totalTime.font = [UIFont systemFontOfSize:12];
            self.totalTime.textColor = WHITECOLOR;
            [self.playBG addSubview:self.totalTime];
            [self.totalTime makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.playProgress.bottom).offset(0);
                make.right.equalTo(self.playProgress.right).offset(0);
                make.width.equalTo(100);
                make.height.equalTo(20);
            }];

//==============================分割线分割线=============*=================

    3.相关方法

    #pragma mark - 音频相关

        -(NSTimer *)timer{
            if (!_timer) {
                _timer=[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateProgress) userInfo:nil repeats:true];
            }
            return _timer;
        }
        
        /**
         *  创建播放器
         *
         *  @return 音频播放器
         */
        -(AVAudioPlayer *)audioPlayer{
            if (!_audioPlayer) {
                NSString *urlStr=[[NSBundle mainBundle]pathForResource:@"华语群星 - 牵丝戏.mp3" ofType:nil];
                NSURL *url=[NSURL fileURLWithPath:urlStr];
                NSError *error=nil;
                //初始化播放器,注意这里的Url参数只能时文件路径,不支持HTTP Url
                _audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
                //设置播放器属性
                _audioPlayer.numberOfLoops=0;//设置为0不循环
                _audioPlayer.delegate=self;
                [_audioPlayer prepareToPlay];//加载音频文件到缓存
                if(error){
                    NSLog(@"初始化播放器过程发生错误,错误信息:%@",error.localizedDescription);
                    return nil;
                }
            }
            return _audioPlayer;
        }
        
        /**
         *  播放音频
         */
        -(void)play{
            if (![self.audioPlayer isPlaying]) {
                [self.audioPlayer play];
                self.timer.fireDate=[NSDate distantPast];//恢复定时器
            }
        }
        
        /**
         *  暂停播放
         */
        -(void)pause{
            if ([self.audioPlayer isPlaying]) {
                [self.audioPlayer pause];
                self.timer.fireDate=[NSDate distantFuture];//暂停定时器,注意不能调用invalidate方法,此方法会取消,之后无法恢复
                
            }
        }
        
        
        /**
         *  更新播放进度
         */
        -(void)updateProgress{
            [UIView animateWithDuration:6 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                float progress = self.audioPlayer.currentTime /self.audioPlayer.duration;
                [self.playProgress setProgress:progress animated:YES];
            } completion:nil];
            
            //    NSLog(@"----progress---%f",progress);
            
            NSInteger time = self.audioPlayer.currentTime;
            self.havTime.text = [NSString stringWithFormat:@"%02ld:%02ld",time/60,time%60];
            //    NSLog(@"----self.havTime.text---%@",self.havTime.text);
        
        
        
        }
        
        #pragma mark - 播放器代理方法
        -(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
            NSLog(@"音乐播放完成...");
            self.playProgress.progress = 0;
            self.playOrPause.selected = !self.playOrPause.selected;         
        }

相关链接
视频和音频
音频相关

上一篇下一篇

猜你喜欢

热点阅读