1、导入头文件:
#import <AVFoundation/AVFoundation.h>2、音乐播放能用到的几个简单的属性
@property (nonatomic,strong) UIProgressView *musicProgress;3、加载一些基本控件
@property (nonatomic,strong) AVAudioPlayer *player;
@property (nonatomic,strong) NSTimer *timer;
-(AVAudioPlayer *)player {
if (!_player) {
//获取音频文件
NSString *music = [[NSBundle mainBundle] pathForResource:@"001" ofType:@"mp3"];
NSURL *musicUrl = [NSURL fileURLWithPath:music];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:musicUrl error:nil];
//循环次数:1
//numberOfLoops = -1 是无限循环
_player.numberOfLoops = 1;
[_player prepareToPlay];
}
return _player;
}
//创建UI控件
-(void)creatrUI {
//创建button
NSArray *array = [NSArray arrayWithObjects:@"开始",@"暂停",@"停止",nil];
for (NSInteger i = 0; i < array.count; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(150, 100 + i *60 , 80, 40);
[btn setTitle:array[i] forState:UIControlStateNormal];
btn.tintColor = [UIColor blueColor];
btn.backgroundColor = [UIColor orangeColor];
btn.tag = 100 + i;
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
//创建音量调节
UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(0, 250, 400, 40)];
[slider addTarget:self action:@selector(sliderValueChange:) forControlEvents:UIControlEventValueChanged];
slider.value = 0.5;
self.player.volume = slider.value;
[self.view addSubview:slider];
//创建进度条
self.musicProgress = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 330, 400, 40)];
self.musicProgress.progressTintColor = [UIColor blueColor];
self.musicProgress.progressViewStyle = UIProgressViewStyleDefault;
[self.view addSubview:self.musicProgress];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self creatrUI];
}
4、实现一些功能的方法:
//获取播放进度
-(void)updateTimer {
// 当前时间/音频的总时间
self.musicProgress.progress = self.player.currentTime / self.player.duration;
}
//音量调节
-(void)sliderValueChange:(UISlider *)slider {
self.player.volume = slider.value;
}
//播放、暂停等功能的实现
-(void)btnClick:(UIButton *)btn {
if (btn.tag == 100) {
NSLog(@"开始");
[self.player play];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
}else if (btn.tag == 101) {
NSLog(@"暂停");
[self.player pause];
}else if (btn.tag == 102) {
NSLog(@"停止");
[self.player stop];
self.player.currentTime = 0;
}
}
/*
<AVAudioPlayerDelegate>
当播放结束后调用:
*/
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
[self.timer invalidate];
}
这样,一个可以实现音乐播放的简单的小程序就完成了,可以自己测试一下