iOS AV Foundation 二維碼掃描使用合成語音朗讀二維碼內容

來源:互聯網
上載者:User

iOS AV Foundation 二維碼掃描使用合成語音朗讀二維碼內容

前一節,我們為程式識別到的二維碼提供了可視化的顯示,這一節,我們使用合成語音朗讀掃描到的二維碼的內容。

修改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];
編譯運行,當程式識別到二維碼時,將用語音朗讀出二維碼的內容。

下一節,我們將為程式添加映像縮放功能。

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.