I am new to iOS
development
and I am developing an app in which I want to play some audios when the QR code
gets detected. I am able to detect the QR code
and also play the audios but the thing is the audio-only plays when I move the camera away from QR code
. So, if I am pointing the camera towards QR code
it does not play the audio but as soon as I move the camera (i.e. no QR code
is getting detected) the audio starts playing. I don't want this behavior I want audio to play as soon as QR code
gets detected. Any suggestion would be great as I have just started iOS
development
2 3 days back. Thanks.
-(void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection(AVCaptureConnection *)connection{
NSString *detected=@"";
if (metadataObjects != nil && [metadataObjects count] > 0) {
AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
detected=[NSString stringWithString:[metadataObj stringValue]];
NSString *path = [[NSBundle mainBundle] pathForResource:@"cbp" ofType:@"mp3"];
NSURL *url = [NSURL URLWithString:path];
_audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:NULL];
[_audioPlayer play];
}
}
}
Don't initialise the AVAudioPlayer
in this AVFoundation
delegate method, Load the player with sound file before scanning start.
(void)loadSound{
NSString *beepFilePath = [[NSBundle mainBundle] pathForResource:@"cbp" ofType:@"mp3"];
NSURL *beepURL = [NSURL URLWithString:beepFilePath];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:beepURL error:&error];
if (error) {
NSLog(@"Could not play sound file.");
NSLog(@"%@", [error localizedDescription]);
}
else{
[_audioPlayer prepareToPlay];
}
}
You can call loadSound()
function in viewWillAppear()
method.And your AVFoundation
delegate method will look like this:-
(void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection(AVCaptureConnection *)connection{
NSString *detected=@"";
if (metadataObjects != nil && [metadataObjects count] > 0) {
AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
detected=[NSString stringWithString:[metadataObj stringValue]];
if (_audioPlayer) {
[_audioPlayer play];
}
}
}
}
try this.