iOS播放MP3音频

1.新建single view工程,导入AVFoundation库

2.ViewController.xib如图



3.ViewController.h文件

?
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
# import <uikit uikit.h= "" >
# import
 
@interface ViewController : UIViewController {
     //进度
     IBOutlet UISlider *_proSlider;
     //声道
     IBOutlet UISlider *_panSlider;
     //速度
     IBOutlet UISlider *_speedSlider;
     //音量
     IBOutlet UISlider *_volSlider;
     IBOutlet UIProgressView *_proV;
     IBOutlet UIProgressView *_proV2;
     
     AVAudioPlayer *_player;
     
     NSTimer *_timer;
}
 
- (IBAction)proSlider:(id)sender;
- (IBAction)panSlider:(id)sender;
- (IBAction)speedSlider:(id)sender;
- (IBAction)volSlider:(id)sender;
 
- (IBAction)play:(id)sender;
- (IBAction)pause:(id)sender;
 
@end </avfoundation></uikit>

4.ViewController.m文件
?
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# import "ViewController.h"
 
@implementation ViewController
 
- ( void )viewDidLoad
{
     [ super viewDidLoad];
     
     NSString *path = [[NSBundle mainBundle] pathForResource:@ "Beat It" ofType:@ "mp3" ];
//    NSURL *url = [NSURL URLWithString:path];//不能这样写,因为是本地路径
     NSURL *url = [NSURL fileURLWithPath:path]; //本地路径应该这样写
     
     _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
     //触发play事件的时候会将mp3文件加载到内存中,然后再播放,所以开始的时候可能按按钮的时候会卡,所以需要prepare
     [_player prepareToPlay];
     //设置支持变速
     _player.enableRate = YES;
     //峰值和平均值
     _player.meteringEnabled = YES;
 
}
 
- ( void )play:(id)sender
{
     //按播放,开始定时器
     _timer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target:self selector: @selector (refresh) userInfo:nil repeats:YES];
     [_player play];
}
 
- ( void )pause:(id)sender
{
     [_player pause];
     //定时器失效
     [_timer invalidate];
}
 
- ( void )refresh
{
     //每隔0.1秒刷新一次进度,当前时间/总时间
     float pro = _player.currentTime/_player.duration;
     [_proSlider setValue:pro animated:YES];
     
     //averagePowerForChannel和peakPowerForChannel的属性分别为声音的最高振幅和平均振幅
     [_player updateMeters]; //不刷新就永远是0
     float pead = ([_player peakPowerForChannel: 0 ]+ 50 )/ 50 ; //0左声道,1右声道
     float ave = ([_player averagePowerForChannel: 0 ]+ 50 )/ 50 ; //同上
     [_proV setProgress:pead animated:YES];
     [_proV2 setProgress:ave animated:YES];
}
 
//进度
- (IBAction)proSlider:(id)sender
{
     //当前时间=总时间*slider.value;
     float curTime = _player.duration*_proSlider.value;
     [_player setCurrentTime:curTime];
}
//声道
- (IBAction)panSlider:(id)sender
{
     _player.pan = _panSlider.value;
}
//速度
- (IBAction)speedSlider:(id)sender
{
     _player.rate = _speedSlider.value;
}
//音量
- (IBAction)volSlider:(id)sender
{
     _player.volume = _volSlider.value;
}
 
@end

你可能感兴趣的:(iOS播放MP3音频)