#import "JPTJ_ViewController.h"
#import "NavigationViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "PureLayout.h"
#define kRecordAudioFile @"myRecord.caf"
@interface JPTJ_ViewController ()<AVAudioPlayerDelegate>
@property (nonatomic,strong) AVAudioPlayer *audioPlayer;//播放器
@property (weak ,nonatomic) NSTimer *timer;//进度更新定时器
@property (strong, nonatomic) UIProgressView *playProgress;//播放进度
@property (strong, nonatomic) UIButton *btn;//播放按钮
@end
@implementation JPTJ_ViewController
{
AVAudioPlayer *player;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
[self NaVigation];
_btn = [[UIButton alloc]init];
_btn.frame = CGRectMake((self.view.frame.size.width-self.view.frame.size.width/100*8)/2, self.view.frame.size.height/100*82, self.view.frame.size.width/100*8, self.view.frame.size.width/100*8);
_btn.backgroundColor = [UIColor brownColor];
[_btn addTarget:self action:@selector(playClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_btn];
_playProgress = [[UIProgressView alloc]init];
_playProgress.frame = CGRectMake(10, self.view.frame.size.height/100*80, self.view.frame.size.width-20, 10);
[self.view addSubview:_playProgress];
}
/**
* 创建播放器
*
* @return 音频播放器
*/
-(AVAudioPlayer *)audioPlayer{
if (!_audioPlayer) {
NSString *urlStr=[[NSBundle mainBundle]pathForResource:@"20160412 125007" ofType:@"m4a"];
NSURL *url=[NSURL fileURLWithPath:urlStr];
NSError *error=nil;
//初始化播放器,注意这里的Url参数只能时文件路径,不支持HTTP Url
_audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
//设置播放器属性
_audioPlayer.numberOfLoops=0;//设置为0不循环
_audioPlayer.delegate=self;
[_audioPlayer prepareToPlay];//加载音频文件到缓存
if(error){
NSLog(@"初始化播放器过程发生错误,错误信息:%@",error.localizedDescription);
return nil;
}
}
return _audioPlayer;
}
/**
* 播放音频
*/
-(void)play{
if (![self.audioPlayer isPlaying]) {
[self.audioPlayer play];
self.timer.fireDate=[NSDate distantPast];//恢复定时器
}
}
/**
* 暂停播放
*/
-(void)pause{
if ([self.audioPlayer isPlaying]) {
[self.audioPlayer pause];
self.timer.fireDate=[NSDate distantFuture];//暂停定时器,注意不能调用invalidate方法,此方法会取消,之后无法恢复
}
}
- (void)playClick:(UIButton *)sender {
if(sender.tag){
sender.tag=0;
[self pause];
}else{
sender.tag=1;
[self play];
}
}
-(NSTimer *)timer{
if (!_timer) {
_timer=[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateProgress) userInfo:nil repeats:true];
}
return _timer;
}
/**
* 更新播放进度
*/
-(void)updateProgress{
float progress= self.audioPlayer.currentTime /self.audioPlayer.duration;
[self.playProgress setProgress:progress animated:true];
}
-(void)NaVigation
{
NavigationViewController *nav = [[NavigationViewController alloc]init];
nav.frame = CGRectMake(0, 0, self.view.frame.size.width, 64);
[nav nacigation:@"音乐播放器" nacigationimage:[UIImage imageNamed:@"nav"] nacigationimage:[UIImage imageNamed:@"Artboard 87.png"]];
[self.view addSubview:nav];
}