iOS录音播放简例-AVFoundation
本例简单介绍一个demo,录制一段声音,再播放它,用的是AVFoundation框架。
一.添加AVFoundation框架,在.m文件中引入
#import <AVFoundation/AVFoundation.h>
二.需要使用的一些类
@property(nonatomic,strong) NSString *recordFilePath; //录音缓存地址
@property(nonatomic,strong) NSURL *recordUrl; //录音url
@property(nonatomic,strong) AVAudioSession *session; //音频控制器
@property(nonatomic,strong) AVAudioRecorder *recorder; //录音控制器
@property(nonatomic,strong) AVAudioPlayer *player; //播放控制器
_recordFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"record.caf"];
_recordUrl = [NSURL fileURLWithPath:self.recordFilePath];
这里存在缓存中,自己也可修改地址。四.录音权限--info.plist
在info.plist中添加键值对,对录音权限进行描述:
五.AVAudioSession管理录音权限
AVAudioSession *session = [AVAudioSession sharedInstance];
if ([session respondsToSelector:@selector(requestRecordPermission:)]){
[session performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
if (granted)
{ //用户同意获取麦克风
dispatch_async(dispatch_get_main_queue(), ^{
//在主线程中是执行录音操作
[self record];
});
}else{}
}];
}
当点击录音按钮后,先执行上面的代码,检查一下用户是否允许录音,允许的话执行[self record]完成录音,不允许的话,可以在else{}中写跳转,跳到设置界面。
六.设置录音控制器,录音
_session = [AVAudioSession sharedInstance];
NSError *sessionError;
[_session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
//判断后台有没有播放
if (_session == nil) {
NSLog(@"Error creating sessing:%@", [sessionError description]);
} else {
//关闭其他音频播放,把自己设为活跃状态
[_session setActive:YES error:nil];
}
//设置AVAudioRecorder
if (!self.recorder) {
NSDictionary *settings = @{AVFormatIDKey : @(kAudioFormatLinearPCM), AVSampleRateKey : @(11025.0), AVNumberOfChannelsKey :@2, AVEncoderBitDepthHintKey : @16, AVEncoderAudioQualityKey : @(AVAudioQualityHigh)};
self.recorder = [[AVAudioRecorder alloc] initWithURL:_recordUrl settings:settings error:nil];
/*
* settings 参数
1.AVNumberOfChannelsKey 通道数 通常为双声道 值2
2.AVSampleRateKey 采样率 单位HZ 通常设置成44100 也就是44.1k,采样率必须要设为11025才能使转化成mp3格式后不会失真
3.AVLinearPCMBitDepthKey 比特率 8 16 24 32
4.AVEncoderAudioQualityKey 声音质量
① AVAudioQualityMin = 0, 最小的质量
② AVAudioQualityLow = 0x20, 比较低的质量
③ AVAudioQualityMedium = 0x40, 中间的质量
④ AVAudioQualityHigh = 0x60,高的质量
⑤ AVAudioQualityMax = 0x7F 最好的质量
5.AVEncoderBitRateKey 音频编码的比特率 单位Kbps 传输的速率 一般设置128000 也就是128kbps
*/
}
//准备记录录音
[_recorder prepareToRecord];
//开启仪表计数功能,开启这个功能,才能检测音频值
[_recorder setMeteringEnabled:YES];
//启动或者恢复记录的录音文件
[_recorder record];
停止录音:
[self.recorder stop];
七.播放录音
NSData *data = [NSData dataWithContentsOfURL:self.recordUrl];
self.player = [[AVAudioPlayer alloc] initWithData:data error:nil];
self.player.volume = 0.5;
[self.player play];