标签:
// 我使用的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 |
|
1
2
3
4
5
|
// 至于控件创建我就不一一写出来了 到这步是初始化播放器self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp3"]] error:nil]; _player.delegate = self; [_player prepareToPlay]; //分配播放所需的资源,并将其加入内部播放队列 (预播放) |
|
1
2
3
4
5
6
7
8
9
10
11
|
// 用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]; |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
// 实现点击按钮播放暂停- (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]; } } |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// 循环播放- (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]; } |
标签:
原文地址:http://www.cnblogs.com/mabao/p/4314137.html