安裝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字符串就可以了,附上運行結果圖,如下: