From: http://hi.baidu.com/loveipon/item/367747a64e1cf639a8cfb7c8
首先引用AVFoundation.framework
.h文件
//用到了拖控件(进度条)
IBOutlet UIProgressView *_progressView;
.m文件
//此方法连接到一个已经拖在视图上的button控件的触发事件上
-(IBAction)play:(id)sender{
//找到要播放的音频
NSString *_path=[[NSBundle mainBundle]pathForResource:@"张玮-high歌 中国好声音"ofType:@"mp3"];
//文件的URL(如果是文件的URL,使用fileURLWithPath)
NSURL *_url=[NSURL fileURLWithPath:_path];
NSError *error;
player=[[AVAudioPlayer alloc]initWithContentsOfURL:_url
error:&error];
if (error) {
NSLog(@"error:%@",[error description]);
return;
}
//准备播放
[player prepareToPlay];
//播放
[player play];
_progressView.progress=0.0f;
//用到了时间触发器,刷新进度条
[NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:@selector(refreshUR:)
userInfo:nil
repeats:YES];
}
//刷新事件
-(void)refreshUR:(NSTimer *)aTimer{
float p=player.currentTime/player.duration;//当前时间、总时间
_progressView.progress=p;
}
//一下三个方法都是连接到已经布置好的BUTTON触发事件上的
//重新播放
player.currentTime=0.0f;
[ player play];
}
//暂停
[ player pause];
}
//停止
-(IBAction)stop:(id)sender{
if ( player.isPlaying) {
[ player stop];
player.currentTime=0.0f;
}
}