三、IOS-AVFoundation音频播放
1、音频会话
1.1、音频会话分类
分类 | 音频输入 | 音频输出 | 混合音 |
Ambient | 支持 | 支持 | |
Solo Ambient | 支持 | ||
Playback | 支持 | 可选 | |
Record | 支持 | ||
Play and Record | 支持 | 支持 | 可选 |
Audio Processing | |||
Multi-Route | 支持 | 支持 |
1.2、音频绘画配置
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
AVAudioSession *session = [AVAudioSession sharedInstance];//获取会话单例
NSError *error;
if (![session setCategory:AVAudioSessionCategoryPlayback error:&error]) {//设置会话
NSLog(@"Category Error: %@", error);
}
if (![session setActive:YES error:&error]) {//激活会话
NSLog(@"Activation Error: %@", error);
}
returnYES;
}
注意:要设备锁屏时还能播放,除了配置设备会话之外,还需到应用的Info.plist文件添加一个名称为Required background modes的数组,并在数组中添加名为App plays audio or streams audio/video using AirPlay的选项。
2、音频播放-AVAudioPlayer
AVFoundation中是AVAudioPlayer是用来播放音频的,只要音频文件不是从网络中获取、需要原始的音频和非常低的延时都可以使用AVAudioPlayer播放音频。
2.1、初始化AVAudioPlayer
NSURL *fileURL = //文件本地路径
NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL
error:&error];
if (!player) {
NSLog(@"Error creating player: %@", error);
}
2.2、AVAudioPlayer的属性
2.2.1、音量-volume(float)
控制播放音量,值介于0.0和1.0之间。
2.2.2、立体声-pan(float)
值介于-1.0到1.0之间,默认值为0.0。
2.2.3、播放率-rate(float)
在修改播放率之前需要将enableRate属性设置为YES,允许用户在不改变音调的情况下调整播放率,值介于0.5和2.0之间。
2.2.4、循环播放-numberOfLoops(NSInteger)
2.2.5、播放时间- currentTime(NSTimeInterval)
2.3、常用方法
- (BOOL)play; 播放音频
- (BOOL)playAtTime:(NSTimeInterval)time;播放音频在指定时间
- (void)pause; 暂停播放
- (void)stop;停止播放