IOS AV Foundation QR code scan read QR code content using synthetic speech
In the previous section, we provided a visual display of the QR code recognized by the program. In this section, we read the content of the scanned QR code from the synthesized speech.
Modify ViewController. m, define and initialize the following instance variables:
AVSpeechSynthesizer *_speechSynthesizer;
_speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
It is very easy to initialize a speech synthesizer. The speech synthesizer controls the playback and sequence of each speech data. After initialization, Metadata output triggers the speech synthesizer to read the content of the scanned QR code.
Tracking QR code changes
Add the following code to the start position of captureOutput: didOutputMetadataObjects: fromConnection:
NSSet *originalBarcodes = [NSSet setWithArray:_barcodes.allValues];
The purpose is to store all detected QR codes before processing a new frame. It is used to compare whether the cached and detected QR codes are the same.
Add the following code to enumerateObjectsUsingBlock}]; then:
NSMutableSet *newBarcodes = [foundBarcodes mutableCopy]; [newBarcodes minusSet:originalBarcodes];
This Code uses the reduce operation of the Set to remove the cached QR code and only retain the newly scanned QR code.
Finally, we use the set operation to remove a QR code that is no longer within the screen range and update the _ barcode dictionary:
NSMutableSet *goneBarcodes = [originalBarcodes mutableCopy]; [goneBarcodes minusSet:foundBarcodes]; [goneBarcodes enumerateObjectsUsingBlock: ^(Barcode *barcode, BOOL *stop) { [_barcodes removeObjectForKey:barcode.metadataObject.stringValue]; }];
Create a "speaking method"
Next, we will set "voice mode" for all the QR code data, including frequency, volume, and pitch. Finally, call speakUtterace to read the QR code:
// 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]; }];
Modify the startRunning method to enable AudioSession:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:0 error:nil]; [[AVAudioSession sharedInstance] setActive:YES error:nil];
Modify stopRunning to disable audio AudioSession:
[[AVAudioSession sharedInstance] setActive:NO error:nil];
Compile and run the program. When the Program recognizes the QR code, it will read the content of the QR code in speech.
In the next section, we will add the image scaling function to the program.