iOS视频直播 -- IJKPlayerDemo

首先感谢bilibili开源的IJK框架~~
由于github限制上传文件大小 ,而IJKFramework文件100多兆,所以就把主要封装代码贴出来了:

.h文件

//
//  AvPlayView.h
//  HQUpgrade
//
//  Created by 杨志勇 on 16/9/21.
//  Copyright © 2016年 zbwx. All rights reserved.
//

#import <UIKit/UIKit.h>

#define videoHeight 184.0

@interface AvPlayView : UIView

@property (nonatomic, copy) NSString *peopleNum;

@property (nonatomic, assign) BOOL needStop; // 默认no

@property (nonatomic, assign) BOOL playEnable; // 默认yes 标志网络情况

@property (nonatomic, copy) void (^intoLivingRoomHandler)(void);

@property (nonatomic, copy) void (^noLoginPlayOverTimeHandler)(void);

@property (nonatomic, copy) void (^closeHandler)(void);

@property (nonatomic, copy) void (^playErrorHandler)(NSString *);

- (void)prepareWithUrlStr:(NSString *)urlStr;

- (void)startPlay;

- (void)pausePlay;

- (void)stopPlay;

- (BOOL)isPlaying;

@end


.m文件

//
//  AvPlayView.m
//  HQUpgrade
//
//  Created by 杨志勇 on 16/9/21.
//  Copyright © 2016年 zbwx. All rights reserved.
//

#import "AvPlayView.h"
#import <IJKMediaFramework/IJKMediaFramework.h>
#import "UIViewExt.h"

//返回颜色
#define kUIColorFromRGB(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

@interface AvPlayView ()
@property (atomic, retain) IJKFFMoviePlayerController<IJKMediaPlayback> *player;
@end

@implementation AvPlayView {
    NSString *_urlStr;
    UILabel *_peopleNumLabel;
    UIButton *_intoLiveRoomBtn;
    NSTimeInterval _currentInterval;
    UIButton *_playIconBtn;
    UIButton *_closeBtn;
    UIImageView *_defalutImg;
    UIImageView *_bottomMaskView;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver: self];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(loadStateDidChange:)
                                                     name:IJKMPMoviePlayerLoadStateDidChangeNotification
                                                   object:_player];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(moviePlayBackFinish:)
                                                     name:IJKMPMoviePlayerPlaybackDidFinishNotification
                                                   object:_player];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(mediaIsPreparedToPlayDidChange:)
                                                     name:IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification
                                                   object:_player];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(moviePlayBackStateDidChange:)
                                                     name:IJKMPMoviePlayerPlaybackStateDidChangeNotification
                                                   object:_player];
        _needStop = NO;
        _playEnable = YES;
        [self addVideoLabelAndButton];
    }
    return self;
}

- (void)closeBtnAction {
    self.closeHandler();
}

- (void)moviePlayBackFinish:(NSNotification*)notification {
    int reason =[[[notification userInfo] valueForKey:IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
    switch (reason) {
        case IJKMPMovieFinishReasonPlaybackEnded:
            NSLog(@"playbackStateDidChange: IJKMPMovieFinishReasonPlaybackEnded: %d\n", reason);
            break;
            
        case IJKMPMovieFinishReasonUserExited:
            NSLog(@"playbackStateDidChange: IJKMPMovieFinishReasonUserExited: %d\n", reason);
            break;
            
        case IJKMPMovieFinishReasonPlaybackError:
            NSLog(@"playbackStateDidChange: IJKMPMovieFinishReasonPlaybackError: %d\n", reason);
            [self pausePlay];
            [self prepareWithUrlStr: _urlStr];
            if (_playErrorHandler) {
                _playErrorHandler(@"获取不到直播源");
            }
            
            break;
            
        default:
            NSLog(@"playbackPlayBackDidFinish: ???: %d\n", reason);
            break;
    }
}

- (void)moviePlayBackStateDidChange:(NSNotification *)notification {

    switch (_player.playbackState) {
        case IJKMPMoviePlaybackStateStopped: {

            break;
        }
        case IJKMPMoviePlaybackStatePlaying: {

            break;
        }
        case IJKMPMoviePlaybackStatePaused: {


            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refreshMediaControl) object:nil];
            break;
        }
        case IJKMPMoviePlaybackStateInterrupted: {

            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refreshMediaControl) object:nil];
            break;
        }
        case IJKMPMoviePlaybackStateSeekingForward:
        case IJKMPMoviePlaybackStateSeekingBackward: {

            break;
        }
        default: {

            break;
        }
    }
}

- (void)loadStateDidChange:(NSNotification*)notification {
    IJKMPMovieLoadState loadState = _player.loadState;
    
    if ((loadState & IJKMPMovieLoadStatePlaythroughOK) != 0) {
        NSLog(@"LoadStateDidChange: IJKMovieLoadStatePlayThroughOK: %d\n",(int)loadState);
    }else if ((loadState & IJKMPMovieLoadStateStalled) != 0) {

    } else {
        NSLog(@"loadStateDidChange: ???: %d\n", (int)loadState);
    }
}

- (void)mediaIsPreparedToPlayDidChange:(NSNotification*)notification {
    NSLog(@"mediaIsPrepareToPlayDidChange\n");
}

- (void)playIconBtnAction:(UIButton *)btn {
    
    if (!_playEnable) {

        return;
    }
    
    [self startPlay];
}

- (BOOL)isPlaying {
//    return [_player isPlaying];
    
    return _playIconBtn.hidden;
}

- (void)refreshMediaControl {

    _currentInterval = [_player currentPlaybackTime];
    if (_needStop) {
        if (_currentInterval >= 120) {
            [self stopPlay];

            _noLoginPlayOverTimeHandler();
        } else {
            [self performSelector:@selector(refreshMediaControl) withObject:nil afterDelay:0.5];
        }
    } else {
        [self performSelector:@selector(refreshMediaControl) withObject:nil afterDelay:0.5];
    }
}

- (void)startPlay {
    
    if (![_player isPlaying]) {
        
        _playIconBtn.hidden = YES;
        
        [self.player prepareToPlay];
        [self.player play];
    }
}


- (void)pausePlay {
    [_player pause];
    _playIconBtn.hidden = NO;
    _defalutImg.hidden = NO;

}

- (void)stopPlay {
    _defalutImg.hidden = NO;

    [_player stop];
    [_player shutdown];
    _player = nil;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refreshMediaControl) object:nil];
}

- (void)intoLiveRoomClick:(UIButton *)btn {

    if (_intoLivingRoomHandler) {
        _intoLivingRoomHandler();
    }
}

- (void)setPeopleNum:(NSString *)peopleNum {
    _peopleNum = peopleNum;
    
    _peopleNumLabel.text = [NSString stringWithFormat: @"观看人数:%@",peopleNum];
}

- (void)prepareWithUrlStr:(NSString *)urlStr {
    
    _currentInterval = 0;
    
    _urlStr = urlStr;
    
    [[_player view] removeFromSuperview];
    
    _player = [[IJKFFMoviePlayerController alloc] initWithContentURL: [NSURL URLWithString:urlStr] withOptions:nil];
    UIView *playerView = [_player view];
    playerView.frame = self.bounds;
    playerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self addSubview:playerView];
    [_player setScalingMode: IJKMPMovieScalingModeAspectFit];
    [playerView addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(tapPlayerViewAction)]];
    
    [self bringSubviewToFront: _defalutImg];
    [self bringSubviewToFront: _playIconBtn];
    [self bringSubviewToFront: _closeBtn];
    [self bringSubviewToFront: _bottomMaskView];
}

- (void)tapPlayerViewAction {
    _bottomMaskView.hidden = !_bottomMaskView.hidden;
}

- (void)addVideoLabelAndButton {
    
    _defalutImg = [[UIImageView alloc] initWithFrame: self.bounds];
    
    _defalutImg.image = [UIImage imageNamed: @"av_default"];

    [self addSubview: _defalutImg];
    _defalutImg.contentMode = UIViewContentModeScaleAspectFill;
    _defalutImg.clipsToBounds = YES;
    _bottomMaskView = [[UIImageView alloc] initWithFrame: CGRectMake(0, self.height - 31, self.width, 31)];
    [self addSubview: _bottomMaskView];
    _bottomMaskView.userInteractionEnabled = YES;
    _bottomMaskView.image = [UIImage imageNamed: @"av_bottom_mask"];
    
    UIImageView *numIconIV = [[UIImageView alloc] initWithFrame: CGRectMake(15, _bottomMaskView.height / 2 - 7, 12, 14)];
    numIconIV.image = [UIImage imageNamed: @"av_count_icon"];
    [_bottomMaskView addSubview: numIconIV];

    UILabel *numLabel = [[UILabel alloc] initWithFrame: CGRectMake(numIconIV.right + 5, 0, 120, _bottomMaskView.height)];
    numLabel.textColor = kUIColorFromRGB(0xffffff);
    numLabel.font = [UIFont systemFontOfSize: 11];
    _peopleNumLabel = numLabel;
    _peopleNumLabel.text = @"";
    [_bottomMaskView addSubview:numLabel];
    
    CGFloat btnWidth = 90;
    CGFloat btnHeight = _bottomMaskView.height;
    
    UIButton *intoLiveRoomBtn = [UIButton buttonWithType: UIButtonTypeCustom];
    intoLiveRoomBtn.frame = CGRectMake(self.width - btnWidth, 0, btnWidth, btnHeight);
    [intoLiveRoomBtn setImage: [UIImage imageNamed: @"av_intoRoom_n"] forState: UIControlStateNormal];
    [intoLiveRoomBtn setTitle: @"进入直播间"  forState: UIControlStateNormal];
    intoLiveRoomBtn.titleLabel.font = [UIFont systemFontOfSize: 11];
    [intoLiveRoomBtn addTarget: self action: @selector(intoLiveRoomClick:) forControlEvents: UIControlEventTouchUpInside];
    [intoLiveRoomBtn setImage:[UIImage imageNamed:@"av_intoRoom_h"] forState:UIControlStateHighlighted];
    [intoLiveRoomBtn setTitleColor: kUIColorFromRGB(0xcccccc) forState:UIControlStateHighlighted];
    _intoLiveRoomBtn = intoLiveRoomBtn;
    [_bottomMaskView addSubview:intoLiveRoomBtn];
    intoLiveRoomBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -24, 0, 24);
    intoLiveRoomBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 52, 0, -52);
    
    UIButton *closeBtn = [UIButton buttonWithType: UIButtonTypeCustom];
    closeBtn.frame = CGRectMake(0, 0, 80, 50);
    [closeBtn setImage: [UIImage imageNamed: @"av_close_n"] forState: UIControlStateNormal];
    [closeBtn setImage: [UIImage imageNamed: @"av_close_h"] forState: UIControlStateHighlighted];
    [self addSubview: closeBtn];
    _closeBtn = closeBtn;
    [closeBtn setImageEdgeInsets: UIEdgeInsetsMake(-3,-6, 3, 6)];
    [closeBtn addTarget: self action: @selector(closeBtnAction) forControlEvents: UIControlEventTouchUpInside];
    
    UIButton *playIconBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [playIconBtn setImage:[UIImage imageNamed:@"simple_player_center_play"] forState:UIControlStateNormal];
    playIconBtn.frame = self.bounds;
    [self addSubview:playIconBtn];
    [playIconBtn addTarget:self action:@selector(playIconBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    _playIconBtn = playIconBtn;

    self.backgroundColor = [UIColor blackColor];
    

}

@end


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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,846评论 25 707
  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一种新的协议。它实...
    香橙柚子阅读 23,800评论 8 183
  • 原谅我,亲爱的 我没有入睡 我独自坐在深夜 静静地 期待着远方 期待着一朵花的绽放 我不知道 远方究竟有多远 我也...
    雨童先生阅读 194评论 0 1
  • 什么事数字化? 就像1000个人眼中有1000个哈姆雷特一样。每个人,每个公司对数字化概念的理解和解读都不一样。行...
    勇敢的北极海燕阅读 477评论 0 0
  • 我多么想和你见一面 看看你最近改变 不再去说从前 只是寒暄 对你说一句 只是说一句 好久不见 1.天青色等烟雨,而...
    羊咿呀嘿阅读 253评论 1 2