由于之前没有做过音频类的项目, 所以这次自己写了一个音频的小Demo能实现暂停播放循环等功能. 直接看代码:
// 我使用的AVAudioPlayer, 首先先导入库文件, 写上头文件,签上代理
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
typedef NS_ENUM(NSInteger, playStatus){ // 这个枚举用来控制暂停和播放的切换
playStatusNo,
playStatusYes,
};
@interface ViewController ()<AVAudioPlayerDelegate>
@property (nonatomic, assign) playStatus staus;
@property (nonatomic, retain) UISlider *slider; // 进度条
@property (nonatomic, retain) UILabel *timeLabel;
@end
// 至于控件创建我就不一一写出来了 到这步是初始化播放器
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp3"]] error:nil];
_player.delegate = self;
[_player prepareToPlay]; //分配播放所需的资源,并将其加入内部播放队列 (预播放)
// 用NSTimer来监控音频播放进度
// 预订一个Timer,设置一个时间间隔。表示输入一个时间间隔对象,以秒为单位,一个>0的浮点类型的值,如果该值<0,系统会默认为0.1 self表发送的对象 useInfo此参数可以为nil,当定时器失效时,由你指定的对象保留和释放该定时器 repeat 为YES时,定时器会不断循环直至失效或被释放,当NO时,定时器会循环发送一次就失效。
_time = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateslider) userInfo:nil repeats:YES];
// 播放次数
UISwitch *loop = [[UISwitch alloc] initWithFrame:CGRectMake(100, 230, 60, 40)];
[loop addTarget:self action:@selector(loopYesOrNo) forControlEvents:UIControlEventValueChanged];
loop.on = NO; // 默认状态不打开
[self.view addSubview:loop];
// 实现点击按钮播放暂停
- (void)buttonClickStart
{
if (self.staus == playStatusYes) {
self.staus = playStatusNo;
[_player pause]; // 暂停播放;
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateMusicTimeLabel) userInfo:self repeats:
YES];
[_button setTitle:@"暂停播放" forState:UIControlStateNormal];
}
else
{
[_player play]; // 开始播放
self.staus = playStatusYes;
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateMusicTimeLabel) userInfo:self repeats:
YES];
[_button setTitle:@"正在播放" forState:UIControlStateNormal];
}
}
// 播放时间更新
-(void)updateMusicTimeLabel{
if ((int)self.player.currentTime % 60 < 10) {
self.timeLabel.text = [NSString stringWithFormat:@"%d:0%d",(int)self.player.currentTime / 60, (int)self.player.currentTime % 60];
} else {
self.timeLabel.text = [NSString stringWithFormat:@"%d:%d",(int)self.player.currentTime / 60, (int)self.player.currentTime % 60];
}
}
// 循环播放
- (void)loopYesOrNo
{
_player.numberOfLoops = -1; // 这里 正数就是播放几次 -1 就是无限循环
}
// 进度条
- (void)updateslider
{
self.slider.value = self.player.currentTime;
}
// 拖动进度条改变播放时间和播放位置
- (void)sliderValueChanged
{
[self.player stop];
[self.player setCurrentTime:self.slider.value];
[self.player prepareToPlay];
[self.player play];
}
其实内容还有很多类似的, 比如说音量的大小和进度条的定义方式差不多而且更简单, 也可以加上静音开关之类的和循环的开关类似.