前一節我們已經把識別到的二維碼以可視化方式呈現,這一節接著讓 App「唸出來」——用語音合成把二維碼內容朗讀出來。這個組合在無障礙、 warehouse 盤點、商品資訊播報等場景中都很實用。
在 ViewController.m 中宣告並初始化:
AVSpeechSynthesizer *_speechSynthesizer;
_speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
初始化非常簡單。語音合成器負責控制各段語音數據的播放與順序。完成後,metadata 輸出回調就會觸發朗讀。
問題在於:掃描回調是逐幀觸發的,同一個二維碼會被連續報告很多次。若不去重,合成器就會不斷重複朗讀同一段文字。解法是用集合做差集運算,只朗讀「這一幀新出現」的碼。
在 captureOutput:didOutputMetadataObjects:fromConnection: 的開頭先快照當前已緩存的所有二維碼:
NSSet *originalBarcodes = [NSSet setWithArray:_barcodes.allValues];
在 enumerateObjectsUsingBlock 的收尾處,用減法扣掉舊的,只留新的:
NSMutableSet *newBarcodes = [foundBarcodes mutableCopy];
[newBarcodes minusSet:originalBarcodes];
最後再把已經離開取景框的碼從緩存字典中移除,避免字典無限膨脹:
NSMutableSet *goneBarcodes = [originalBarcodes mutableCopy];
[goneBarcodes minusSet:foundBarcodes];
[goneBarcodes enumerateObjectsUsingBlock:^(Barcode *barcode, BOOL *stop) {
[_barcodes removeObjectForKey:barcode.metadataObject.stringValue];
}];
AVSpeechUtterance 支援調整語速、音量與音高。下面只朗讀新出現的二維碼:
[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];
}];
播放語音前必須設定 AVAudioSession 的類別,否則在靜音鍵開啟時可能沒有聲音。在 startRunning 中啟用:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
withOptions:0
error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
在 stopRunning 中停用,釋放音頻資源:
[[AVAudioSession sharedInstance] setActive:NO error:nil];
編譯執行,當 App 識別到新的二維碼時,就會以語音朗讀其內容。
小提醒:連續掃到多個碼時,utterance 會排隊朗讀,若希望「只唸最後一個」,可以在推入新 utterance 前先呼叫 [_speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate]。
下一節,我們將為程式加上圖像縮放功能。