音频和视频播放器的简单实现

/**
 本页面集成音频和视频播放器
 主要步骤和思路如下
 音频:
 1、导入音频依赖的库#import <AVFoundation/AVFoundation.h>
 2、设置音频播放需要的控件:时间、音量的Label和Slider、播放和暂停按钮
 3、设置音频播放器,加载音频
 4、关联音频播放的内容和控件的事件
    1)获取音频的时间长度关联时间相关的slider
    2)关联音频音量slider和音频音量
    3)给播放和暂停的按钮上添加点击事件,在事件处理的方法中控制播放或者暂停

 视频:
 1、导入视频依赖的库#import <AVFoundation/AVFoundation.h>
 2、实例一个UIView-->videoPlayView 用来添加AVPlayerLayer,因为视频播放器需要在AVPlayerLayer上才可以播放
 2、设置视频播放需要的控件:时间连个的Label和Slider、播放和暂停按钮
 3、设置视频播放器,加载视频
 4、关联视频播放的内容和控件的事件
    1)获取获取的时间长度关联时间相关的slider,设置当前播放的时间和总的时间长
    2)关联Slider的进度和播放的进度
    3)给播放和暂停的按钮上添加点击事件,在事件处理的方法中控制播放或者暂停


 另外:
 本界面通过SegmentController 来控制音频和视频的显示和隐藏
 */


#import "MdeiaViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "Definition.h"

@interface MdeiaViewController ()
{
    //记录音视频切换的时候原本音频是否在播放
    BOOL isPlay;
    //记录视频是否在播放
    BOOL videoIsPaly;
}
@property(nonatomic,strong)AVAudioPlayer  *musicPlayer;//音频播放器
@property(nonatomic,strong)UIView *videoPlayView;//用来添加Avplayer的View
@property(nonatomic,strong)AVPlayer *player;//用来视频播放器

@end

@implementation MdeiaViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置背景图片
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"IMG_0029"]];

    //头部视图,返回键
    headView *headview = [[headView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    [headview.btn addTarget:self action:@selector(CloseVC) forControlEvents:UIControlEventTouchUpInside];
    headview.label.text = @"流媒体";
    [self.view addSubview:headview];

    //初始化segmentCtl
    [self initSegmentCtl];

    //初始化音频面板
    [self initMusicPlayerView];

    //加载音频文件
    self.musicPlayer =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"情非得已" ofType:@"mp3"]] error:nil];

    //检测文件是否可以被播放
    if ([self.musicPlayer prepareToPlay]) {

        UISlider *timeSlider = [self.view viewWithTag:13];
        timeSlider.maximumValue = self.musicPlayer.duration;
        NSLog(@"%f",self.musicPlayer.duration);

        UISlider *voiceSlicer = [self.view viewWithTag:14];
        //voiceSlicer.maximumValue = self.musicPlayer.v
        voiceSlicer.value = self.musicPlayer.volume;

    }
    else{
        NSLog(@"加载失败");

    }



    //设置videView的相关控件
    [self initVideoView];

    //将容器视图videoPlayView 添加到self.view上
    [self.view addSubview:self.videoPlayView];

    //播放器图层,并在播放器图层上添加播放器。
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];

    //设置播放图层大小
    playerLayer.frame = self.videoPlayView.frame;
    playerLayer.videoGravity = AVLayerVideoGravityResize;

    //将播放图层作为自图层添加到videoPlayerView图层上。
    [self.videoPlayView.layer addSublayer: playerLayer];
    [self.player.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    self.videoPlayView.hidden = YES;

}
//设置segmentCtl
-(void)initSegmentCtl{
    NSArray *itemArray = @[@"音频播放器",@"视频播放器"];

    UISegmentedControl *segmentCtl = [[UISegmentedControl alloc]initWithItems:itemArray];
    [segmentCtl setTintColor:[UIColor colorWithRed:0.833 green:1.000 blue:0.509 alpha:1.000]];
    segmentCtl.frame = CGRectMake(0, 64, SCREEN_WIDTH, 44);
    segmentCtl.selectedSegmentIndex = 0;
    [segmentCtl addTarget:self action:@selector(itemDidSelected:) forControlEvents:UIControlEventValueChanged];


    [self.view addSubview:segmentCtl];


}

//初始化音乐播放器的界面
-(void)initMusicPlayerView{
    //初始化一个view,用来添加播放相关控件
    UIView *musicView = [[UIView alloc]initWithFrame:CGRectMake(0, 108, SCREEN_WIDTH, 360)];
    musicView.tag = 9;

    //在view底部放一个用户查看具体实现的
    UIButton *detailBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 360-60, SCREEN_WIDTH, 60)];
    detailBtn.backgroundColor = [UIColor colorWithRed:0.966 green:1.000 blue:0.055 alpha:0.800];
    [detailBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [detailBtn setTitle:@"查看具体实现" forState:UIControlStateNormal];
    [detailBtn  addTarget:self action:@selector(showDetail) forControlEvents:UIControlEventTouchUpInside];
    [musicView addSubview:detailBtn];

    //时间label
    UILabel *timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 45, 60, 20)];
    timeLabel.backgroundColor = [UIColor clearColor];
    timeLabel.text =@"时间";
    timeLabel.textColor = [UIColor orangeColor];
    [musicView addSubview:timeLabel];

    //时间slider
    UISlider *timeSlider = [[UISlider alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2.0-100, 50, 240, 8)];
    timeSlider.minimumValue = 0;
    timeSlider.maximumValue = 1;
    timeSlider.tag = 13;
    timeSlider.tintColor = [UIColor orangeColor];
    [timeSlider addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    [musicView addSubview:timeSlider];

    //声音label
    UILabel *voiceLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 95, 60, 20)];
    voiceLabel.backgroundColor = [UIColor clearColor];
    voiceLabel.text =@"音量";
    voiceLabel.textColor = [UIColor redColor];
    [musicView addSubview:voiceLabel];
    //音量slider
    UISlider *voiceSlider = [[UISlider alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2.0-100, 100, 240, 8)];
    voiceSlider.minimumValue = 0;
    voiceSlider.maximumValue = 1;
    voiceSlider.tintColor = [UIColor redColor];
    voiceSlider.tag = 14;
    [voiceSlider addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    [musicView addSubview:voiceSlider];
    //播放按钮
    UIButton *playBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2.0-120, 220, 100, 40)];
    playBtn.backgroundColor = [UIColor colorWithRed:0.872 green:1.000 blue:0.303 alpha:1.000];
    [playBtn setTitle:@"播放" forState:UIControlStateNormal];
    playBtn.tag = 11;
    playBtn.layer.cornerRadius = 10;
    [playBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [playBtn addTarget:self action:@selector(playOrPause:) forControlEvents:UIControlEventTouchUpInside];

    [musicView addSubview:playBtn];

    //暂停按钮
    UIButton *pauseBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2.0+20, 220, 100, 40)];
    pauseBtn.backgroundColor = [UIColor grayColor];
    [pauseBtn setTitle:@"暂停" forState:UIControlStateNormal];
    pauseBtn.tag = 12;
    pauseBtn.layer.cornerRadius = 10;
    [pauseBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [pauseBtn addTarget:self action:@selector(playOrPause:) forControlEvents:UIControlEventTouchUpInside];
    [musicView addSubview:pauseBtn];

    [self.view addSubview:musicView];

}
//segmentCtl 被点击后的相应处理
-(void)itemDidSelected:(UISegmentedControl*)segCtl{


    switch (segCtl.selectedSegmentIndex) {
        case 0:
        {   //点击音频播放器的时候隐藏视频播放器的View
            self.videoPlayView.hidden = YES;
            UIView *videoView = [self.view viewWithTag:29];
            videoView.hidden = YES;


            //显示音频播放器的view
            UIView *view = [self.view viewWithTag:9];
            view.hidden = NO;
            //检测上次的隐藏时的状态,如果是播放的话,继续播放
            if (isPlay == YES) {
                [self.musicPlayer play];
            }

//            UIView *videView = [self.view viewWithTag:29];
//            videView.hidden = YES;
            //当切换到音频的时候暂停视频的播放,并改变按钮的颜色
            [self.player pause];






        }
            break;

        default:{
            //选中为视频播放器的时候
            self.videoPlayView.hidden = NO;
            UIView *videoView = [self.view viewWithTag:29];
            videoView.hidden = NO;


            //隐藏音频播放器
            UIView *view = [self.view viewWithTag:9];
            view.hidden = YES;
            //记录上播放的结果
            if (self.musicPlayer.isPlaying == YES) {
                isPlay = YES;
                [self.musicPlayer pause];
            }else
            {
                isPlay = NO;
            }

            UIButton *playBtn = [self.view viewWithTag:41];
            playBtn.backgroundColor = [UIColor colorWithRed:0.872 green:1.000 blue:0.303 alpha:1.000];
            UIButton *pauseBtn = [self.view viewWithTag:42];
            pauseBtn.backgroundColor = [UIColor grayColor];




        }
            break;
    }


}
-(void)CloseVC{


    //当界面关闭的时候将音视频清空,移除观察者,防止内存泄漏
    [self.musicPlayer stop];
     self.musicPlayer = nil;


    [self.player pause];
    [self.player setRate:0];
    [self.player.currentItem removeObserver:self forKeyPath:@"status" context:nil];
    [self.player replaceCurrentItemWithPlayerItem:nil];
    self.player = nil;


    [self dismissViewControllerAnimated:YES completion:^{

    }];


}
-(void)dealloc{

    NSLog(@"如果打印了说明没有内存泄漏");

}
//
-(void)change{

     UISlider *timeSlider = [self.view viewWithTag:13];
    timeSlider.value = self.musicPlayer.currentTime;

    if (timeSlider.value == self.musicPlayer.duration) {

        UIButton *playBtn = [self.view viewWithTag:11];
        playBtn.enabled = YES;
        playBtn.backgroundColor = [UIColor colorWithRed:0.872 green:1.000 blue:0.303 alpha:1.000];
        UIButton *pauseBtn = [self.view viewWithTag:12];
        pauseBtn.enabled = YES;
        pauseBtn.backgroundColor = [UIColor grayColor];
    }


}
//判断点击的是播放还是暂停,做出相应的反应
-(void)playOrPause:(UIButton*)btn{


    switch (btn.tag) {
        case 11:
        {//musicplaybtn
            [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(change) userInfo:nil repeats:YES];
            btn.backgroundColor =[UIColor grayColor];
            btn.enabled = NO;
            [self.musicPlayer play];
            UIButton *pausebtn = [self.view viewWithTag:12];
            pausebtn.backgroundColor = [UIColor colorWithRed:0.872 green:1.000 blue:0.303 alpha:1.000];
            pausebtn.enabled = YES;


        }
            break;
        case 12:
        {//musicpuasebtn
            btn.backgroundColor = [UIColor grayColor];
            btn.enabled = NO;
            UIButton *playBtn = [self.view viewWithTag:11];
            playBtn.backgroundColor = [UIColor colorWithRed:0.872 green:1.000 blue:0.303 alpha:1.000];
            playBtn.enabled = YES;
            [self.musicPlayer pause];

        }
            break;
        case 41:
        {//videoplaybtn
            btn.backgroundColor = [UIColor grayColor];
            UIButton *videoPauseBtn = [self.view viewWithTag:42];
            videoPauseBtn.backgroundColor = [UIColor colorWithRed:0.872 green:1.000 blue:0.303 alpha:1.000];
            [self.player play];


        }
            break;

        default:{
        //videopause
            btn.backgroundColor = [UIColor grayColor];
            UIButton *videoPlayBtn = [self.view viewWithTag:41];
            videoPlayBtn.backgroundColor = [UIColor colorWithRed:0.872 green:1.000 blue:0.303 alpha:1.000];
            [self.player pause];


        }
            break;
    }


}
//跳转到具体实现
-(void)showDetail{


}
//判断是哪一个Slider的改变,并做出相应改变
-(void)valueChanged:(UISlider *)slider
{
    switch (slider.tag) {
        case 13:
        {//使音频播放的时间调整到滑块当前的时间
            self.musicPlayer.currentTime = slider.value;

        }
            break;
        case 14:
        {//使音频的声音调整到滑块的音频大小
            self.musicPlayer.volume = slider.value;

        }

        default:
        {
            //跳转到滑块的时间开始播放视频
            [self.player seekToTime:CMTimeMake(slider.value, 1)];

        }
            break;
    }


}
-(UIView*)videoPlayView
{
    if (!_videoPlayView) {

        _videoPlayView = [[UIView alloc]initWithFrame:CGRectMake(0, 108, SCREEN_WIDTH, 240)];
        //_videoPlayView
        _videoPlayView.backgroundColor = [UIColor colorWithWhite:1.000 alpha:0.000];
    }
    return _videoPlayView;


}
//初始化播放器,并在播放器上添加播放资源
-(AVPlayer*)player
{
    if (!_player) {
        AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp4"]]];
        _player = [AVPlayer playerWithPlayerItem:playerItem];
    }
    return _player;


}
//设置视频播放器的相关控件
-(void)initVideoView{

    UIView *videoView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-240, SCREEN_WIDTH, 300)];
    videoView.backgroundColor = [UIColor clearColor];
    videoView.tag = 29;
    videoView.hidden = YES;

    //在view底部放一个用户查看具体实现的
    UIButton *detailBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 240-60, SCREEN_WIDTH, 60)];
    detailBtn.backgroundColor = [UIColor colorWithRed:0.966 green:1.000 blue:0.055 alpha:0.800];
    [detailBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [detailBtn setTitle:@"查看具体实现" forState:UIControlStateNormal];
    [detailBtn  addTarget:self action:@selector(showDetail) forControlEvents:UIControlEventTouchUpInside];
    detailBtn.tag = 31;
    [videoView addSubview:detailBtn];

    //时间label
    UILabel *timeLabel1 = [[UILabel alloc]initWithFrame:CGRectMake(10, 55, 160, 20)];
    timeLabel1.backgroundColor = [UIColor clearColor];
    timeLabel1.text =@"00:00:00";
    timeLabel1.textAlignment = NSTextAlignmentLeft;
    timeLabel1.tag = 32;
    timeLabel1.textColor = [UIColor orangeColor];
    [videoView addSubview:timeLabel1];

    UILabel *timeLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-170, 55, 160, 20)];
    timeLabel2.backgroundColor = [UIColor clearColor];
    timeLabel2.text =@"00:00:00";
    timeLabel2.textAlignment = NSTextAlignmentRight;
    timeLabel2.tag = 33;
    timeLabel2.textColor = [UIColor orangeColor];
    [videoView addSubview:timeLabel2];


    //时间slider
    UISlider *timeSlider = [[UISlider alloc]initWithFrame:CGRectMake(0,40, SCREEN_WIDTH, 8)];
    timeSlider.minimumValue = 0;
    timeSlider.maximumValue = 1;
    timeSlider.tag = 34;
    timeSlider.tintColor = [UIColor orangeColor];
    [timeSlider addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    [videoView addSubview:timeSlider];

    //播放按钮
    UIButton *playBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2.0-120, 100, 100, 40)];
    playBtn.backgroundColor = [UIColor colorWithRed:0.872 green:1.000 blue:0.303 alpha:1.000];
    [playBtn setTitle:@"播放" forState:UIControlStateNormal];
    playBtn.tag = 41;
    playBtn.layer.cornerRadius = 10;
    [playBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [playBtn addTarget:self action:@selector(playOrPause:) forControlEvents:UIControlEventTouchUpInside];

    [videoView addSubview:playBtn];

    //暂停按钮
    UIButton *pauseBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2.0+20, 100, 100, 40)];
    pauseBtn.backgroundColor = [UIColor grayColor];
    [pauseBtn setTitle:@"暂停" forState:UIControlStateNormal];
    pauseBtn.tag = 42;
    pauseBtn.layer.cornerRadius = 10;
    [pauseBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [pauseBtn addTarget:self action:@selector(playOrPause:) forControlEvents:UIControlEventTouchUpInside];
    [videoView addSubview:pauseBtn];



    [self.view addSubview:videoView];



}
//添加观察当播放的内容进度改变的时候,改变时间Label上的显示
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{

    if (object == self.player.currentItem) {
        if ([change[@"new"] integerValue] == AVPlayerStatusReadyToPlay) {
            NSLog(@"加载完成,可以播放");

            UISlider *videoTimeSlider = [self.view viewWithTag:34];

            NSInteger totalSeconds = self.player.currentItem.duration.value/self.player.currentItem.duration.timescale;

            videoTimeSlider.maximumValue = totalSeconds;

            UILabel *totalTimeLabel = [self.view viewWithTag:33];

            totalTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld:%02ld",totalSeconds/3600,totalSeconds%3600/60,totalSeconds%60];

            UILabel *currentLabel = [self.view viewWithTag:32];
            //防止循环引用
          //  __weak MdeiaViewController *weakSelf = self;

            [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:nil usingBlock:^(CMTime time) {

                NSInteger currentTime = time.value/time.timescale;

                videoTimeSlider.value = currentTime;

                currentLabel.text = [NSString stringWithFormat:@"%02ld:%02ld:%02ld",currentTime/3600,currentTime%3600/60,currentTime%60];
            }];




        }
    }


}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值