ios wav格式语音文件转文字
一、录音设置
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init];
//设置录音格式 AVFormatIDKey==kAudioFormatLinearPCM
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
//设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量)
[recordSetting setValue:[NSNumber numberWithFloat:16000] forKey:AVSampleRateKey];
//录音通道数 1 或 2
[recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
//线性采样位数 8、16、24、32
[recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
//录音的质量
[recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
NSString *strUrl = [NSString stringWithFormat:@"%@/%@.wav", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], [NSString uuid]];
NSURL *url = [NSURL fileURLWithPath:strUrl];
self.recordUrlKey = strUrl;
// self.audioRecord.filePath = strUrl;
NSError *error;
//初始化
_recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&error];
//开启音量检测
self.recorder.meteringEnabled = YES;
if ([self.recorder prepareToRecord]){
return YES;
}
二、wav 转 m4a 格式
NSURL *audioPath = [NSURL fileURLWithPath:path];
AVURLAsset* audioAsset = [[AVURLAsset alloc] initWithURL:audioPath options:nil];
AVAssetExportSession* exportSession = [[AVAssetExportSession alloc] initWithAsset:audioAsset presetName:AVAssetExportPresetAppleM4A];
NSURL* exportURL = [NSURL fileURLWithPath:[[path componentsSeparatedByString:@".wav"] objectAtIndex:0]];
NSURL* destinationURL = [exportURL URLByAppendingPathExtension:@"m4a"];
exportSession.outputURL = destinationURL;
exportSession.outputFileType = AVFileTypeAppleM4A;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
if (AVAssetExportSessionStatusCompleted == exportSession.status) {
} else if (AVAssetExportSessionStatusFailed == exportSession.status) {
} else {
}
didFinish();
}];
三、m4a 翻译
NSURL *exportURL = [NSURL fileURLWithPath:[[path componentsSeparatedByString:@".wav"] objectAtIndex:0]];
NSURL *destinationURL = [exportURL URLByAppendingPathExtension:@"m4a"];
NSLocale *local =[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
SFSpeechRecognizer *localRecognizer =[[SFSpeechRecognizer alloc] initWithLocale:local];
NSURL *url = destinationURL;
if (!url) { [AlertUtil showAlertWithText:@"转换失败"]; return;}
SFSpeechURLRecognitionRequest *res =[[SFSpeechURLRecognitionRequest alloc] initWithURL:url];
__weak typeof(self) weakSelf = self;
[localRecognizer recognitionTaskWithRequest:res resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
if (error) {
NSLog(@"------------------------语音识别解析======失败,%@",error);
[AlertUtil showAlertWithText:@"转换失败"];
} else {
NSLog(@"------------------------语音识别解析======成功,%@",result.bestTranscription.formattedString);
[weakSelf showWord:result.bestTranscription.formattedString];
}
}];