利用系统框架AVFoundation实现录音和录音播放
1,导入头文件
#import <AVFoundation/AVFoundation.h>
2,申请麦克风权限NSMicrophoneUsageDescription
3,属性定义
@property (nonatomic, strong) AVAudioRecorder * audioRecorder;//录音器
@property (nonatomic, strong) AVAudioPlayer *player; //播放器
@property (nonatomic, strong) NSURL *recordFileUrl; //文件地址
-(AVAudioRecorder *)audioRecorder
{
if (!_audioRecorder) {
// 1. 确定录音存放的位置
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"text.caf"];
NSURL *url = [NSURL URLWithString:path];
// 2. 设置录音参数
NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init];
// 设置编码格式
[recordSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey: AVFormatIDKey];
// 采样率
[recordSettings setValue :[NSNumber numberWithFloat:11025.0] forKey: AVSampleRateKey];
// 通道数
[recordSettings setValue :[NSNumber numberWithInt:2] forKey: AVNumberOfChannelsKey];
//音频质量,采样质量
[recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
// 3. 创建录音对象
_audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:nil];
}
return _audioRecorder;
}
4,开始录音
//准备录音
[self.audioRecorder prepareToRecord];
//开始录音
[self.audioRecorder record];
// 几秒后开始录音
// [self.audioRecorder recordAtTime:self.audioRecorder.deviceCurrentTime + 5];
// 录音录多久
//[self.audioRecorder recordForDuration:5];
5,结束录音
if (self.audioRecorder.currentTime>2) {
[self.audioRecorder stop];
}else{
NSLog(@"录音时间不超过2秒,删除");
[self.audioRecorder stop];
[self.audioRecorder deleteRecording];
}
6,播放声音
if ([self.player isPlaying])return;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.recordFileUrl error:nil];
[self.player play];
网友评论