iOS开发之语音录制
首先我们需要进行麦克风访问授权
AVAudioSessionRecordPermission permission = [[AVAudioSession sharedInstance] recordPermission]; //判断是否授权 if (AVAudioSessionRecordPermissionUndetermined == permission) { [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) { //授权回调操作 }]; } else { //用户没有同意授权 }
在授权成功之后再执行录音操作代码
//首先设置录音模式 AVAudioSession *session = [AVAudioSession sharedInstance]; NSError *sessionError; /* AVAudioSessionCategoryPlayAndRecord :录制和播放 AVAudioSessionCategoryAmbient :用于非以语音为主的应用,随着静音键和屏幕关闭而静音. AVAudioSessionCategorySoloAmbient :类似AVAudioSessionCategoryAmbient不同之处在于它会中止其它应用播放声音。 AVAudioSessionCategoryPlayback :用于以语音为主的应用,不会随着静音键和屏幕关闭而静音.可在后台播放声音 AVAudioSessionCategoryRecord :用于需要录音的应用,除了来电铃声,闹钟或日历提醒之外的其它系统声音都不会被播放,只提供单纯录音功能. */ [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError]; [session setActive:YES error:nil]; // 录音参数 NSDictionary *setting = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,// 编码格式 [NSNumber numberWithFloat:8000], AVSampleRateKey, //采样率 [NSNumber numberWithInt:1], AVNumberOfChannelsKey, //通道数 [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey, //采样位数(PCM专属) [NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved, //是否允许音频交叉(PCM专属) [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey, //采样信号是否是浮点数(PCM专属) [NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey, //是否是大端存储模式(PCM专属) [NSNumber numberWithInt:AVAudioQualityMax], AVEncoderAudioQualityKey, //音质 nil]; NSString *filePath = @"";//设置录音文件的存储路径 self.recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:filePath] settings:setting error:nil]; self.recorder.delegate = self; //开启音频测量 self.recorder.meteringEnabled = YES; [self.recorder prepareToRecord]; [self.recorder record];
结束录音方法
//结束播放 if (self.recorder != nil) { [self.recorder stop]; }
最后就可以在之前设置的录音文件路径目录读取音频数据
同时有个录音代理回调方法也可以处理
AVAudioRecorderDelegate
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag { //录音技术操作 //录音模式结束后需要将模式调整回来 AVAudioSession *audioSession = [AVAudioSession sharedInstance]; [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil]; } - (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error { //录音失败调用 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!