一、简单说明
音乐播放用到一个叫做AVAudioPlayer的类,这个类可以用于播放手机本地的音乐文件。
注意:
(1)该类(AVAudioPlayer)只能用于播放本地音频。
(2)时间比较短的(称之为音效)使用AudioServicesCreateSystemSoundID来创建,而本地时间较长(称之为音乐)使用AVAudioPlayer类。
二、代码示例
AVAudioPlayer类依赖于AVFoundation框架,因此在头文件内导入 #import <AVFoundation/AVFoundation.h>
提示:代码中创建的AVAudioPlayer播放器不能是一个局部变量,这样在- (void)viewDidLoad中加载一次就是消失。应该调整为全局属性。
1 #import "LCLViewController.h"
2 #import <AVFoundation/AVFoundation.h> // 导入头文件
3
4 @interface LCLViewController ()
5 @property(nonatomic,strong)AVAudioPlayer *audioplayer; // 成为全局属性
6 @end
7
8 @implementation LCLViewController
9
10 - (void)viewDidLoad
11 {
12 [super viewDidLoad];
13
14 }
15
16 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
17 {
18
19 //1.音频文件的url路径
20 NSURL *url=[[NSBundle mainBundle]URLForResource:@"235319.mp3" withExtension:Nil];
21
22 //2.创建播放器(注意:一个AVAudioPlayer只能播放一个url)
23 self.audioplayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:Nil];
24
25 //3.缓冲
26 [self.audioplayer prepareToPlay];
27
28 //4.播放
29 [self.audioplayer play];
30 }
31
32 @end
播放、暂停和停止。
代码如下:
1 #import "LCLViewController.h"
2 #import <AVFoundation/AVFoundation.h>
3
4 @interface LCLViewController ()
5 @property(nonatomic,strong)AVAudioPlayer *player;
6 - (IBAction)play;
7 - (IBAction)pause;
8 - (IBAction)stop;
9 @end
10
11 @implementation LCLViewController
12
13 #pragma mark-懒加载
14 -(AVAudioPlayer *)player
15 {
16 if (_player==Nil) {
17
18 //1.音频文件的url路径
19 NSURL *url=[[NSBundle mainBundle]URLForResource:@"235319.mp3" withExtension:Nil];
20
21 //2.创建播放器(注意:一个AVAudioPlayer只能播放一个url)
22 self.player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:Nil];
23
24 //3.缓冲
25 [self.player prepareToPlay];
26 }
27 return _player;
28 }
29
30 - (void)viewDidLoad
31 {
32 [super viewDidLoad];
33 }
34
35 - (IBAction)play {
36 //开始播放/继续播放
37 [self.player play];
38 }
39
40 - (IBAction)pause {
41 //暂停
42 [self.player pause];
43 }
44
45 - (IBAction)stop {
46 //停止
47 //注意:如果点击了stop,那么一定要让播放器重新创建,否则会出现一些莫名其面的问题
48 [self.player stop];
49 self.player=Nil;
50 }
51 @end
四、播放多个文件
点击,url,按住common建查看。
可以发现,这个url是只读的,因此只能通过initWithContentsOfUrl的方式进行设置,也就意味着一个播放器对象只能播放一个音频文件。
// 代码自己在iOS8.4上亲测可用,代码可以直接copy到自己的项目中用。
原文:http://www.cnblogs.com/LiuChengLi/p/4871132.html