安装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字符串就可以了,附上运行结果图,如下: