前一節,我們為程式識别到的二維碼提供了可視化的顯示,這一節,我們使用合成語音朗讀掃描到的二維碼的内容。
修改ViewController.m,定義以下執行個體變量并進行初始化:
AVSpeechSynthesizer *_speechSynthesizer;
_speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
初始化語音合成器十分簡單。語音合成器會控制對每個語音資料的回放和順序。初始化完成後,Metadata output将觸發語音合成器來朗讀掃描到的二維碼的内容。
跟蹤二維碼的變化
添加以下代碼到captureOutput:didOutputMetadataObjects:fromConnection:的開始位置:
NSSet *originalBarcodes = [NSSet setWithArray:_barcodes.allValues];
目的是在處理一個新的frame前,将所有檢測到的二維碼存儲起來。用于比較已經緩存的二維碼和新檢測到的二維碼是否相同。
添加以下代碼到enumerateObjectsUsingBlock的"}];"之後:
NSMutableSet *newBarcodes = [foundBarcodes mutableCopy];
[newBarcodes minusSet:originalBarcodes];
這段代碼利用集合的減操作,去除已經緩存了的二維碼,隻保留新掃描到的二維碼。
最後,我們再次利用集合操作移除已經不在螢幕範圍内的二維碼,并更新_barcode字典:
NSMutableSet *goneBarcodes = [originalBarcodes mutableCopy];
[goneBarcodes minusSet:foundBarcodes];
[goneBarcodes enumerateObjectsUsingBlock: ^(Barcode *barcode, BOOL *stop) {
[_barcodes removeObjectForKey:barcode.metadataObject.stringValue];
}];
建立“說話方式”
接下來,我們為所有二維碼資料設定“說話方式”,包括頻率、音量、音高。最後調用speakUtterace:朗讀出二維碼的内容:
// Speak the new barcodes
[newBarcodes enumerateObjectsUsingBlock:^(Barcode *barcode, BOOL *stop) {
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:barcode.metadataObject.stringValue];
utterance.rate = AVSpeechUtteranceMinimumSpeechRate + ((AVSpeechUtteranceMaximumSpeechRate - AVSpeechUtteranceMinimumSpeechRate) * 0.5f);
utterance.volume = 1.0f;
utterance.pitchMultiplier = 1.2f;
[_speechSynthesizer speakUtterance:utterance];
}];
修改startRunning方法,使能AudioSession:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:0 error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
修改stopRunning方法,禁用音頻AudioSession:
[[AVAudioSession sharedInstance] setActive:NO error:nil];
編譯運作,當程式識别到二維碼時,将用語音朗讀出二維碼的内容。
下一節,我們将為程式添加圖像縮放功能。
轉載請注明出處:http://blog.csdn.net/yamingwu/article/details/44535513