音频缓冲播放 DOUAudioStreamer框架

安装DOUAudioStreamer框架

这里就不叙述了,安装cocopods

还有源码用到了SDCycleScrollView框架,支持cocopods安装,其他的就直接上源码了


#import "BaseViewController.h"

#import

@interfacePreViewController :BaseViewController

- (instancetype) initWithPicArray:(NSArray*)picArray mp3_path:(NSString*)mp3_path detailString:(NSString*)detailString titleString:(NSString*)titleString;

@property (copy, nonatomic) NSArray *regardArray;

@property (strong, nonatomic) NSTimer *timer;

@end


#import "PreViewController.h"

#import "SDCycleScrollView.h"

#import "XH_LyricScrollView.h"

#import "Track.h"

#import

@interface PreViewController ()

@property (copy, nonatomic) NSArray *picArray;

@property (copy, nonatomic) NSString *mp3_path;

@property (copy, nonatomic) NSString *detailString;

@property (copy, nonatomic) NSString *titleString;

@property (weak, nonatomic) UILabel *progressLabel;

@property (weak, nonatomic) UILabel *totalLabel;

@property (strong, nonatomic) UISlider *slider;

@property (strong, nonatomic) UIProgressView *progress;

@property (strong, nonatomic) XH_LyricScrollView *vScrollView;

@property (strong, nonatomic) Track *audioTrack;

@property (strong, nonatomic) DOUAudioStreamer *streamer;

@property (nonatomic,assign) BOOL sliding;

@end

@implementationPreViewController

- (void) viewWillAppear:(BOOL)animated

{

    [superviewWillAppear:animated];

    self.navigationController.navigationBar.hidden = YES;


}

- (void) viewWillDisappear:(BOOL)animated

{

    [super viewWillDisappear:animated];

    self.navigationController.navigationBar.hidden = NO;

    [self backaction];

}

- (instancetype)initWithPicArray:(NSArray*)picArray mp3_path:(NSString*)mp3_path detailString:(NSString*)detailString titleString:(NSString*)titleString

{

    if(self= [superinit]) {

        self.picArray= picArray;self.mp3_path= mp3_path;self.detailString= detailString;self.titleString= titleString;

    }

    return self;

}

- (void)popVC{


    [self.navigationController popViewControllerAnimated:YES];

}

- (void)viewDidLoad {

    [super viewDidLoad];

    [self createUI];

    if (self.regardArray.count > 0) {

        self.vScrollView = [[XH_LyricScrollView alloc] initWithFrame:SCREEN_FRAME];

        [self.view addSubview:self.vScrollView];

        [self.vScrollView setScrollTitles:self.regardArray ScrollTime:2];

    }


    //音乐为空不需要创建播放控件

    SCLog(@"%@",self.mp3_path);

    if ([self.mp3_path rangeOfString:@"mp3"].location != NSNotFound && self.mp3_path != nil) {

        [self setupPlayView];

        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(_timerAction:) userInfo:nil repeats:YES];

    }

    [self setNavBar];

}

//头部导航部分

- (void)setNavBar

{

    UIView *navBar = [[UIView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 40)];

    [self.viewaddSubview:navBar];


    UIButton *leftItem = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 20, 20)];

    [leftItemsetImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];

    [leftItemaddTarget:self action:@selector(popVC) forControlEvents:UIControlEventTouchUpInside];

    [navBaraddSubview:leftItem];


    UILabel *centerLabelItem = [[UILabel alloc] initWithFrame:CGRectZero];

    centerLabelItem.text=self.titleString;

    centerLabelItem.textColor= [UIColorwhiteColor];

    [centerLabelItemsizeToFit];

    centerLabelItem.center= navBar.center;

    centerLabelItem.centerY= leftItem.centerY;

    [navBaraddSubview:centerLabelItem];


}

- (void)createUI

{

    self.view.backgroundColor = [UIColor blackColor];

    //轮播图

    SDCycleScrollView *lunboView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, -20, SCREEN_WIDTH, SCREEN_HEIGHT + 20) imageNamesGroup:self.picArray];

    lunboView.showPageControl=NO;

    [self.viewaddSubview:lunboView];

}

- (void)setupPlayView

{

    UIView*playView = [[UIViewalloc]initWithFrame:CGRectMake(0,SCREEN_HEIGHT- 44 - 14,SCREEN_WIDTH, 44)];

    [self.viewaddSubview:playView];


    UIButton*playButton = [[UIButtonalloc]init];

    [playButtonsetImage:[UIImage imageNamed:@"btn_paly"] forState:UIControlStateNormal];

    [playButtonaddTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];

    [playViewaddSubview:playButton];


    UILabel*progressLabel = [[UILabelalloc]init];

    progressLabel.text=@"00:00";

    progressLabel.textColor = [UIColor whiteColor];

    [progressLabelsizeToFit];

    progressLabel.width= progressLabel.width+ 5;

    progressLabel.textAlignment = NSTextAlignmentCenter;

    self.progressLabel= progressLabel;

    [playViewaddSubview:progressLabel];


    self.progress = [[UIProgressView alloc] init];

    self.progress.trackTintColor = [UIColor grayColor];

    self.progress.progressTintColor = [UIColor whiteColor];

    [playViewaddSubview:self.progress];



    self.slider = [[UISlider alloc] init];

    self.slider.tintColor = [UIColor yellowColor];

    self.slider.maximumTrackTintColor = [UIColor clearColor];

    self.slider.continuous =YES;

    [self.slider addTarget:self action:@selector(_actionSliderProgress:) forControlEvents:UIControlEventValueChanged];

    [self.slider addTarget:self action:@selector(durationSliderTouchEnded:) forControlEvents:UIControlEventTouchUpInside];

    [playViewaddSubview:self.slider];


    UILabel *totalLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_slider.frame) + 10, 13, 0, 14)];

    totalLabel.text=@"--:--";

    totalLabel.textColor = [UIColor whiteColor];

    [totalLabelsizeToFit];

    self.totalLabel= totalLabel;

    [playViewaddSubview:totalLabel];


    [playButtonmas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.equalTo(playView).with.offset(5);

        make.top.equalTo(playView).with.offset(10);

        make.height.width.mas_equalTo(@34);

    }];


    [progressLabelmas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.equalTo(playButton.mas_right).with.offset(5);

        make.centerY.equalTo(playButton.mas_centerY);

        make.height.mas_equalTo(@14);

        make.width.mas_equalTo(@50);

    }];


    [self.progress mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.equalTo(progressLabel.mas_right).with.offset(5);

        make.right.equalTo(totalLabel.mas_left).with.offset(-5);

        make.centerY.equalTo(playButton.mas_centerY);

        make.height.mas_equalTo(@4);

    }];


    [totalLabelmas_makeConstraints:^(MASConstraintMaker *make) {

        make.right.equalTo(playView).with.offset(-5);

        make.centerY.equalTo(playButton.mas_centerY);

        make.height.mas_equalTo(@14);

        make.width.mas_equalTo(@50);

    }];


    [self.slider mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.mas_equalTo(self.progress.mas_left);

        make.top.mas_equalTo(self.progress.mas_top).offset(-10);

        make.height.mas_equalTo(20);

        make.right.equalTo(self.progress.mas_right);

    }];


    self.audioTrack = [[Track alloc] init];

    self.audioTrack.audioFileURL = [NSURL URLWithString:self.mp3_path];

    [self createPlayer];


}

- (void)createPlayer{

    //// 如果要实现全局播放的播放器,,可以把播放器的创建使用单利创建。。。

    self.streamer = [DOUAudioStreamer streamerWithAudioFile:self.audioTrack];

    [self.streamer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:@"kStatusKVOKey"];

    [self.streamer addObserver:self forKeyPath:@"duration"options:NSKeyValueObservingOptionNew context:@"kDurationKVOKey"];

    [self.streamer addObserver:self forKeyPath:@"bufferingRatio"options:NSKeyValueObservingOptionNew context:@"kBufferingRatioKVOKey"];

    [self.streamer play];

}

- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context{

    if(context ==@"kStatusKVOKey") {

        [selfperformSelector:@selector(_updateStatus)

                     onThread:[NSThread mainThread]

                   withObject:nil

                waitUntilDone:NO];

    }elseif(context ==@"kDurationKVOKey") {

        [selfperformSelector:@selector(_timerAction:)

                     onThread:[NSThread mainThread]

                   withObject:nil

                waitUntilDone:NO];

    }else if (context == @"kBufferingRatioKVOKey") {

    }else{

        [superobserveValueForKeyPath:keyPathofObject:objectchange:changecontext:context];

    }

}

- (void)_updateStatus{

    switch ([_streamer status]) {

        case DOUAudioStreamerPlaying:


            break;

        case DOUAudioStreamerPaused:


            break;

        case DOUAudioStreamerIdle:

            break;

        case DOUAudioStreamerFinished:

            /// 当前音频播放完成,,播放下一个音频

            break;

        case DOUAudioStreamerBuffering:

            break;

        case DOUAudioStreamerError:

            break;

    }

}

//// 计时器 显示 播放进度 时间

- (void)_timerAction:(id)timer{

    NSLog(@"%lf",[_streamer duration]);

    if([_streamerduration] == 0.0) {

        [self.slider setValue:0.0f animated:NO];

    }else{

        /// 播放进度条  self.sliding bool值 在滑动进度调试设置为yes 暂时停止进度条赋值。。

        if(self.sliding==YES) {


        }else{  // 滑动结束后正常赋值

            self.slider.maximumValue = self.streamer.duration;

            [self.slider setValue:[_streamer currentTime] animated:YES];

        }

        // 当前播放时间

        doubleminutesElapsed =floor(fmod([_streamercurrentTime]/ 60.0,60.0));

        doublesecondsElapsed =fmod([_streamercurrentTime],60.0);

        self.progressLabel.text= [NSStringstringWithFormat:@"%02.0f:%02.0f",minutesElapsed, secondsElapsed];


        // 音频总时长

        doubleminutesElapsedtotal =floor(fmod([_streamerduration]/ 60.0,60.0));

        doublesecondsElapsedtotal =ceil(fmod([_streamerduration],60.0));

        self.totalLabel.text= [NSStringstringWithFormat:@"%02.0f:%02.0f",minutesElapsedtotal, secondsElapsedtotal];

    }

    /// 缓冲进度

    self.progress.progress = [_streamer bufferingRatio];

}

/// 播放器销毁

- (void)_cancelStreamer{

    if(_streamer!=nil) {

        [_streamer pause];

        [_streamer removeObserver:self forKeyPath:@"status"];

        [_streamer removeObserver:self forKeyPath:@"duration"];

        [_streamer removeObserver:self forKeyPath:@"bufferingRatio"];

        _streamer=nil;

    }

}

// 此为进度条开始滑动的方法 ,,具体在uislider 创建的时候添加

- (void)_actionSliderProgress:(id)sender{

    self.sliding=YES;

}

// 此为进度条滑动结束的方法 ,,具体在uislider 创建的时候添加

- (void)durationSliderTouchEnded:(UISlider*)slider{

    /// 延时0.5秒 再给进度条赋值,,防止滑动进度条结束时会产生回弹。。

    [selfperformSelector:@selector(reloadprogressValue)withObject:selfafterDelay:0.5];

    /// 跳到指定时间播放

    [_streamer setCurrentTime:[slider value]];

}

- (void)reloadprogressValue{

    self.sliding=NO;

}

/// 播放 暂停按钮点击方法

- (void)playButtonAction{

    if ([_streamer status] == DOUAudioStreamerPaused ||

        [_streamer status] == DOUAudioStreamerIdle) {

        [_streamer play];

        [self.timer setFireDate:[NSDate distantPast]];

    }else{

        [_streamer pause];

        [self.timer setFireDate:[NSDate distantFuture]];

    }

}

/// 返回按钮 销毁计时器和播放器

- (void)backaction{

    [_timer invalidate];

    _timer=nil;

    [self _cancelStreamer];

    [self dismissViewControllerAnimated:YES completion:^{


    }];

}

- (void)play:(UIButton*)sender

{

    if ([_streamer status] == DOUAudioStreamerPaused ||

        [_streamer status] == DOUAudioStreamerIdle) {

        [sendersetImage:[UIImage imageNamed:@"btn_paly"] forState:UIControlStateNormal];

        [_streamer play];

        [self.timer setFireDate:[NSDate distantPast]];

    }else{

        [sendersetImage:[UIImage imageNamed:@"btn_suspend"] forState:UIControlStateNormal];

        [_streamer pause];

        [self.timer setFireDate:[NSDate distantFuture]];

    }

}

- (void) getRegardJsonData:(NSString*)urlString greetingID:(NSString*)greetingID

{

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    hud.mode = MBProgressHUDModeIndeterminate;

    hud.bezelView.style = MBProgressHUDBackgroundStyleBlur;

    hud.bezelView.color = [UIColor blackColor];

    hud.label.text=@"加载中...";

    hud.label.textColor = [UIColor whiteColor];

    [hudshowAnimated:YES];


    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    NSDictionary*objDict = [userDefaultsobjectForKey:@"obj"];

    NSString*memberID = objDict[@"memberID"];

    NSString*token = objDict[@"token"];


    NSDictionary*paramter = @{@"memberID": memberID,

                               @"token": token,

                               @"greetingID": greetingID

                               };

    SCLog(@"%@-----%@",urlString,paramter);

    [[NetPackageAFN shareHttpManager] netWorkType:NetWorkPOST Signature:nil Token:nil URLString:urlString Parameters:paramter Success:^(id json) {

        SCLog(@"---%@",json);

        if ([[json[@"obj"] class] isSubclassOfClass:[NSNull class]]) {

        }

    }Failure:^(NSError*error) {

        NSLog(@"%@",error.localizedDescription);

    }];

}

- (void)dealloc

{


}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end


以上为全部的源码,只要传入图片url和mp3格式的url字符串就可以了,附上运行结果图,如下:


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

推荐阅读更多精彩内容