iOS10新特性之Speech新框架

1硫麻、前言
在這之前瞎疼,我相信大家都知道CIDetector能夠做到人臉檢測這一功能吧仲吏,注意是檢測并不是識(shí)別濒析,如果要做到識(shí)別的話也即區(qū)別人臉的異同就要用到OpenCV了正什,說了這么多就是要引出蘋果在今年新推出的Speech新框架,能夠做到語音識(shí)別~~~額号杏,其實(shí)只是能夠做到把一段語音轉(zhuǎn)化成文字婴氮。

2、框架主要類



#import <Foundation/Foundation.h>

#import <Speech/SFSpeechRecognitionResult.h>
#import <Speech/SFSpeechRecognitionRequest.h>
#import <Speech/SFSpeechRecognitionTask.h>
#import <Speech/SFSpeechRecognitionTaskHint.h>
#import <Speech/SFSpeechRecognizer.h>
#import <Speech/SFTranscriptionSegment.h>
#import <Speech/SFTranscription.h>

3盾致、怎么用

#import "NFSpeechViewController.h"
#import <Speech/Speech.h>

@interface NFSpeechViewController ()<SFSpeechRecognitionTaskDelegate>

@property (nonatomic ,strong) SFSpeechRecognitionTask *recognitionTask;
@property (nonatomic ,strong) SFSpeechRecognizer      *speechRecognizer;
@property (nonatomic ,strong) UILabel                 *recognizerLabel;

@end

@implementation NFSpeechViewController

- (void)dealloc {
    [self.recognitionTask cancel];
    self.recognitionTask = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    //0.0獲取權(quán)限
    //0.1在info.plist里面配置
    /*
     typedef NS_ENUM(NSInteger, SFSpeechRecognizerAuthorizationStatus) {
     SFSpeechRecognizerAuthorizationStatusNotDetermined,
     SFSpeechRecognizerAuthorizationStatusDenied,
     SFSpeechRecognizerAuthorizationStatusRestricted,
     SFSpeechRecognizerAuthorizationStatusAuthorized,
     };
     */
    [SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
        switch (status) {
            case SFSpeechRecognizerAuthorizationStatusNotDetermined:
                NSLog(@"NotDetermined");
                break;
            case SFSpeechRecognizerAuthorizationStatusDenied:
                NSLog(@"Denied");
                break;
            case SFSpeechRecognizerAuthorizationStatusRestricted:
                NSLog(@"Restricted");
                break;
            case SFSpeechRecognizerAuthorizationStatusAuthorized:
                NSLog(@"Authorized");
                break;
            default:
                break;
        }
    }];
    
    //1.創(chuàng)建SFSpeechRecognizer識(shí)別實(shí)例
    self.speechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];

    //2.創(chuàng)建識(shí)別請(qǐng)求
    SFSpeechURLRecognitionRequest *request = [[SFSpeechURLRecognitionRequest alloc] initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"游子吟.mp3" ofType:nil]]];
    
    //3.開始識(shí)別任務(wù)
    self.recognitionTask = [self recognitionTaskWithRequest1:request];
}

- (SFSpeechRecognitionTask *)recognitionTaskWithRequest0:(SFSpeechURLRecognitionRequest *)request{
    return [self.speechRecognizer recognitionTaskWithRequest:request resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"語音識(shí)別解析正確--%@", result.bestTranscription.formattedString);
        }else {
            NSLog(@"語音識(shí)別解析失敗--%@", error);
        }
    }];
}

- (SFSpeechRecognitionTask *)recognitionTaskWithRequest1:(SFSpeechURLRecognitionRequest *)request{
    return [self.speechRecognizer recognitionTaskWithRequest:request delegate:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark- SFSpeechRecognitionTaskDelegate

// Called when the task first detects speech in the source audio
- (void)speechRecognitionDidDetectSpeech:(SFSpeechRecognitionTask *)task {

}

// Called for all recognitions, including non-final hypothesis
- (void)speechRecognitionTask:(SFSpeechRecognitionTask *)task didHypothesizeTranscription:(SFTranscription *)transcription {

}

// Called only for final recognitions of utterances. No more about the utterance will be reported
- (void)speechRecognitionTask:(SFSpeechRecognitionTask *)task didFinishRecognition:(SFSpeechRecognitionResult *)recognitionResult {
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont systemFontOfSize:18],
                                 };
    
    CGRect rect = [recognitionResult.bestTranscription.formattedString boundingRectWithSize:CGSizeMake(self.view.bounds.size.width - 100, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    self.recognizerLabel.text = recognitionResult.bestTranscription.formattedString;
    self.recognizerLabel.frame = CGRectMake(50, 120, rect.size.width, rect.size.height);
}

// Called when the task is no longer accepting new audio but may be finishing final processing
- (void)speechRecognitionTaskFinishedReadingAudio:(SFSpeechRecognitionTask *)task {

}

// Called when the task has been cancelled, either by client app, the user, or the system
- (void)speechRecognitionTaskWasCancelled:(SFSpeechRecognitionTask *)task {
    
}

// Called when recognition of all requested utterances is finished.
// If successfully is false, the error property of the task will contain error information
- (void)speechRecognitionTask:(SFSpeechRecognitionTask *)task didFinishSuccessfully:(BOOL)successfully {
    if (successfully) {
        NSLog(@"全部解析完畢");
    }
}

#pragma mark- getter

- (UILabel *)recognizerLabel {
    if (!_recognizerLabel) {
        _recognizerLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 120, self.view.bounds.size.width - 100, 100)];
        _recognizerLabel.numberOfLines = 0;
        _recognizerLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
        _recognizerLabel.adjustsFontForContentSizeCategory = YES;
        _recognizerLabel.textColor = [UIColor orangeColor];
        [self.view addSubview:_recognizerLabel];
    }
    return _recognizerLabel;
}

@end

上面一坨代碼就是新框架的一個(gè)簡單的不能在簡單的例子主经,你可以復(fù)制代碼試一試,你可以創(chuàng)建一個(gè)和我同名的類庭惜,這樣直接拷貝上面代碼就可以了罩驻。

4、步驟解析
首先护赊、我們要做的就是獲取權(quán)限惠遏,蘋果對(duì)權(quán)限安全這一面是做了很大的改進(jìn)的,通過iOS10關(guān)于權(quán)限的新特性不難看出來骏啰。

權(quán)限.png

通過上圖节吮,我們需要在info.plist配置文件中添加對(duì)應(yīng)的權(quán)限,這次iOS10更新之后我們終于不需要像以前那樣Copy判耕、Paste了透绩,因?yàn)橛休斎胩崾玖藒~~~開心

其次、接下來就是創(chuàng)建SFSpeechRecognizer實(shí)例了
這里需要提一下的就是本地化語言的坑壁熄,如果你不知道

[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]

@"zh_CN"字符串的話帚豪,你可以使用

[SFSpeechRecognizer supportedLocales];

進(jìn)行查看,選取合適的使用草丧,這里@"zh"在iOS9之后就不是簡體中文了狸臣,而是TW繁體中文,簡體中文就要使用@"zh_CN"了!!!!

for (NSLocale *lacal in [SFSpeechRecognizer supportedLocales].allObjects) {
        NSLog(@"countryCode:%@  languageCode:%@ ", lacal.countryCode, lacal.languageCode);
}

第2步 創(chuàng)建識(shí)別請(qǐng)求昌执,就簡單了直接把要識(shí)別的語音url傳進(jìn)去就行了(這里使用的是本地資源)

第3步中開始識(shí)別任務(wù)我用的是delegate的方式在代理方法中去做處理固棚,蘋果還提供了block方式。對(duì)應(yīng)的代碼:

- (SFSpeechRecognitionTask *)recognitionTaskWithRequest0:(SFSpeechURLRecognitionRequest *)request{
    return [self.speechRecognizer recognitionTaskWithRequest:request resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"語音識(shí)別解析正確--%@", result.bestTranscription.formattedString);
        }else {
            NSLog(@"語音識(shí)別解析失敗--%@", error);
        }
    }];
}

- (SFSpeechRecognitionTask *)recognitionTaskWithRequest1:(SFSpeechURLRecognitionRequest *)request{
    return [self.speechRecognizer recognitionTaskWithRequest:request delegate:self];
}

怎么識(shí)別我已經(jīng)在代碼新的很清楚了仙蚜,按照步驟來就可以了,注釋也很清楚厂汗。
好啦~~
趕緊試試去吧~~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末委粉,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子娶桦,更是在濱河造成了極大的恐慌贾节,老刑警劉巖汁汗,帶你破解...
    沈念sama閱讀 222,729評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異栗涂,居然都是意外死亡知牌,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門斤程,熙熙樓的掌柜王于貴愁眉苦臉地迎上來角寸,“玉大人,你說我怎么就攤上這事忿墅”馀海” “怎么了?”我有些...
    開封第一講書人閱讀 169,461評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵疚脐,是天一觀的道長亿柑。 經(jīng)常有香客問我,道長棍弄,這世上最難降的妖魔是什么望薄? 我笑而不...
    開封第一講書人閱讀 60,135評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮呼畸,結(jié)果婚禮上痕支,老公的妹妹穿的比我還像新娘。我一直安慰自己役耕,他們只是感情好采转,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,130評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著瞬痘,像睡著了一般故慈。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上框全,一...
    開封第一講書人閱讀 52,736評(píng)論 1 312
  • 那天察绷,我揣著相機(jī)與錄音,去河邊找鬼津辩。 笑死拆撼,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的喘沿。 我是一名探鬼主播闸度,決...
    沈念sama閱讀 41,179評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼蚜印!你這毒婦竟也來了莺禁?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,124評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤窄赋,失蹤者是張志新(化名)和其女友劉穎哟冬,沒想到半個(gè)月后楼熄,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,657評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡浩峡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,723評(píng)論 3 342
  • 正文 我和宋清朗相戀三年可岂,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片翰灾。...
    茶點(diǎn)故事閱讀 40,872評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡缕粹,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出预侯,到底是詐尸還是另有隱情致开,我是刑警寧澤,帶...
    沈念sama閱讀 36,533評(píng)論 5 351
  • 正文 年R本政府宣布萎馅,位于F島的核電站双戳,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏糜芳。R本人自食惡果不足惜飒货,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,213評(píng)論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望峭竣。 院中可真熱鬧塘辅,春花似錦、人聲如沸皆撩。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,700評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽扛吞。三九已至呻惕,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間滥比,已是汗流浹背亚脆。 一陣腳步聲響...
    開封第一講書人閱讀 33,819評(píng)論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留盲泛,地道東北人濒持。 一個(gè)月前我還...
    沈念sama閱讀 49,304評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像寺滚,于是被迫代替她去往敵國和親柑营。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,876評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,332評(píng)論 25 707
  • 我也夢(mèng)想環(huán)游世界村视,和心愛之人一起看遍世界的一草一木官套;我也夢(mèng)想居于別墅,保姆繞身,司機(jī)接送虏杰;我更清楚,我一睜眼看到的...
    飯飯a閱讀 326評(píng)論 0 2
  • 昨天的懶惰都是今天打在臉上的巴掌勒虾。 之前我在一篇文章看過類似的觀點(diǎn)纺阔,所以以下僅陳述我自己的一些親身經(jīng)歷。 剛?cè)ド洗?..
    罐子小姐閱讀 262評(píng)論 0 0
  • 自然可作名詞修然,亦可作形容詞笛钝。前者為吾所喜,融入自然愕宋,能靜玻靡,靜而生動(dòng); 后者乃畢生之追求中贝,所謂“道法自然”囤捻,求道求自...
    曉風(fēng)閱讀 465評(píng)論 1 2
  • 2017年7月月7日 親愛的天父爸爸,我感恩您的帶領(lǐng)邻寿,把我安置在神的家中蝎土,盡情地享受您的愛,弟兄姐妹的愛绣否,家人的愛...
    陳小蘭閱讀 222評(píng)論 0 0