IOS10新出的speech(演講,講話)框架,可以方便的將語音轉(zhuǎn)化為文字 。

在使用之前,首先介紹幾個需要用的類 ,使用方法類似webView
SFSpeechRecognizer (Speech:演講? Recognizer:識別)
SFSpeechRecognitionRequest (識別請求)
SFTranscription (Transcription:譯文)
SFTranscriptionSegment (Segment :段)
先創(chuàng)建一個SFSpeechRecognizer ? ? 類似創(chuàng)建一個webView
然后傳入求個識別請求 ? ? ? ? ? ? ? ? ? ? ?類似webView的網(wǎng)絡(luò)請求
然后設(shè)置代理,監(jiān)聽返回結(jié)果。
在使用之前語音之前 先在info.plist里面添加這個key,否則會崩潰
<key>NSSpeechRecognitionUsageDescription</key>
<string>測試語音 ?</string>
這個是使用錄音功能添加的 ?語音不需要
<key>NSMicrophoneUsageDescription</key>
<string>測試錄音 </string>
- (void)speechRecognitionTask:(SFSpeechRecognitionTask *)task didFinishRecognition:(SFSpeechRecognitionResult *)recognitionResult{}
這個代理方法里面返回recognitionResult :
recognitionResult的兩個屬性
@property (nonatomic, readonly, copy) SFTranscription *bestTranscription;
// Hypotheses for possible transcriptions, sorted in decending order of confidence (more likely first)
@property (nonatomic, readonly, copy) NSArray*transcriptions;
bestTranscription : 返回了最可能的一條表達譯文數(shù)據(jù)
transcriptions:所有的可能的識別數(shù)據(jù)
SFTranscription的一個屬性
@property(nonatomic,readonly,copy)NSArray<SFTranscriptionSegment>*segments;
你所說的一句話,可能是有好幾個詞語拼成的,transcription就是你所說的那句話,segments就是你所說的你那句話的組成每個單詞的集合。SFTranscriptionSegment包含該每個單詞信息,比如說這個單詞所用的時間。
錄音:(好像文章結(jié)構(gòu)有點亂)
錄音使用 AVAudioRecorder
錄音后的文件 這里保存在了 這個路徑里面
NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
return [documentPath stringByAppendingPathComponent:@"test.aac"];
關(guān)于錄音里面的一些參數(shù)的設(shè)置,demo里面給了較多的注釋和講解。
這里面的錄音,每次新錄的會覆蓋原來的錄音
錄音完成后轉(zhuǎn)化為文字:
- (void)speechRecognitionTask:(SFSpeechRecognitionTask *)task didFinishRecognition:(SFSpeechRecognitionResult *)recognitionResult?
錄音轉(zhuǎn)化完成會調(diào)用這個方法。
NSLog(@"完成錄音轉(zhuǎn)換? %@",recognitionResult.bestTranscription);
取這個recognitionResult.bestTranscription 就是轉(zhuǎn)化完成的語句。不過這個轉(zhuǎn)化完成的語句有個缺點就是它只是一長句話,中間沒有什么標點符號。并不像微信里面的那么智能。
對轉(zhuǎn)化后的文字的處理:
這個我也沒有什么好的辦法。百度上找了好多,介紹的文章也就是到此為止。
這里筆者就是把轉(zhuǎn)化后的每句話做了判斷:
如果一句話中的某個片段,時間大于0.6秒 后面就需要拼接標點
根據(jù)這個片段的最后一個字,拼接相應(yīng)的標點
if (speechString.length == 0) return @"";
NSString *lastString = [speechString substringFromIndex:speechString.length? - 1];
if ([lastString isEqualToString:@"啊"]) {
return @"!";
}else if ([lastString isEqualToString:@"吧"])
{
return @"~";
}else if ([lastString isEqualToString:@"呢"]){
return @"?";
}else if ([lastString isEqualToString:@"哈"]) {
return @"~~";
}else {
return @",";
}
最后希望有大神能對文章以及后面的這個標點符號的處理多多指正 ~~~~非常感激