iOS中录制音频的简单示例
全栈老韩
全栈工程师,擅长iOS App开发、前端(vue、react、nuxt、小程序&Taro)开发、Flutter、React Native、后端(midwayjs、golang、express、koa)开发、docker容器、seo优化等。
直接看代码吧
// 音频文件目录
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *folder = [path stringByAppendingString:@"/Audio"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:folder]){ // 如果不存在,那么建立这个文件夹
[fileManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:nil];
}
// 时间戳
NSDate *date = [NSDate date];
NSInteger timeInterval = [date timeIntervalSince1970]*1000;
NSString *timeStamp = [NSString stringWithFormat:@"%ld", timeInterval];
// 音频文件完整路径
NSString *fileFullName = [NSString stringWithFormat:@"%@.aac", timeStamp];
NSString *storePath = [path stringByAppendingPathComponent:fileFullName];
NSError *error = nil;
// 初始化录音机
NSDictionary *setting = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kAudioFormatMPEG4AAC],AVFormatIDKey,
[NSNumber numberWithInt:44100],AVSampleRateKey,
[NSNumber numberWithInt:1],AVNumberOfChannelsKey,
[NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
[NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
[NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
nil];
AVAudioRecorder *recorder = [[AVAudioRecorder alloc]
initWithURL:[NSURL URLWithString:path]
settings:setting
error:&error];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error: nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
if (![session setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionMixWithOthers
error:&setCategoryError]) {
// handle error
NSLog(@"Failed to setup audio session %@", setCategoryError.description);
if(callBack) {
callBack(NO, 4, @"录音链接建立失败");
}
} else {
if(callBack) {
callBack(YES, 1, @"录音链接建立成功");
}
[recorder prepareToRecord];
[recorder recordForDuration:audioMaxDuration];
}
发布于2024-02-02 11:18:28
浏览量55·
暂无评论,快来发表第一条评论吧