IOS音频播放组件
1、与音频相关的头文件等都在AVFoundation.h中,所以第一步是添加音频库文件:
#import <AVFoundation/AVFoundation.h>
2、先找一段要播放的音频文件,我这里找到是一个mp3文件,然后添加到项目中:
3、使用NSBundle获取这个文件并转化成NSData类型:
NSString *filepath = [[NSBundle mainBundle]pathForResource:@"bbb" ofType:@"mp3"];
NSData *data = [[NSData data]initWithContentsOfFile:filepath];
4、声明一个全局变量的AVAudioPlayer对象player:
@interface ViewController (){
AVAudioPlayer *player;
}
@end
5、初始化全局变量player:
player = [[AVAudioPlayer alloc]initWithData:data error:nil];
6、添加一个开始、暂停播放的按钮:
UIButton *myBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 200, 214, 80)];
myBtn.backgroundColor = [UIColor orangeColor];
myBtn.layer.cornerRadius = 20;
myBtn.layer.masksToBounds = YES;
myBtn.enabled = YES;
[myBtn setTitle:@"开始播放" forState:UIControlStateNormal];
[myBtn addTarget:self action:@selector(myBtnAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:myBtn];
7、编写按钮的方法,点击按钮之后检测player是否在播放,如果在播放,就停止播放,如果未播放,就开始播放,其中停止播放和开始播放调用的是player对象的play方法和pause方法:
-(void)myBtnAction :(UIButton*)sender{
if (player.playing) {
[player pause];
[sender setTitle:@"开始按钮" forState:UIControlStateNormal];
}else{
[player play];
[sender setTitle:@"暂停按钮" forState:UIControlStateNormal];
}
}
模拟运行并点击按钮就可以听到美妙的音乐了。
以下是完整代码:
1 //
2 // ViewController.m
3 // ceshi
4 //
5 // Created by mac on 16/5/24.
6 // Copyright © 2016年 mzw. All rights reserved.
7 //
8
9 #import "ViewController.h"
10 #import <AVFoundation/AVFoundation.h>
11
12 @interface ViewController (){
13 AVAudioPlayer *player;
14 }
15
16 @end
17
18 @implementation ViewController
19
20 - (void)viewDidLoad {
21 [super viewDidLoad];
22
23 // 获取项目树中的音频文件
24 NSString *filepath = [[NSBundle mainBundle]pathForResource:@"bbb" ofType:@"mp3"];
25 // 把获取的音频文件转化为nsdata类型
26 NSData *data = [[NSData data]initWithContentsOfFile:filepath];
27
28 // 初始化一个音频播放器
29 player = [[AVAudioPlayer alloc]initWithData:data error:nil];
30
31 // 创建一个button,点击button开始或暂停音频播放器的播放
32 UIButton *myBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 200, 214, 80)];
33 myBtn.backgroundColor = [UIColor orangeColor];
34 myBtn.layer.cornerRadius = 20;
35 myBtn.layer.masksToBounds = YES;
36 myBtn.enabled = YES;
37 [myBtn setTitle:@"开始播放" forState:UIControlStateNormal];
38 [myBtn addTarget:self action:@selector(myBtnAction:) forControlEvents:UIControlEventTouchUpInside];
39 [self.view addSubview:myBtn];
40
41
42 }
43
44
45 -(void)myBtnAction :(UIButton*)sender{
46 // 如果音频播放器处于播放状态,点击后就暂停播放,如果处于未播放状态,就开始播放
47 if (player.playing) {
48 [player pause];
49 [sender setTitle:@"开始按钮" forState:UIControlStateNormal];
50 }else{
51 [player play];
52 [sender setTitle:@"暂停按钮" forState:UIControlStateNormal];
53 }
54 }
55 @end
文章出处:http://www.cnblogs.com/jiwangbujiu/p/5522650.html