iOS 语音识别

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/sinat_30162391/article/details/83097007
  • 添加MobileCoreServices.framework
  • info.plist Privacy - Microphone Usage Description
  • info.plist Privacy - Speech Recognition Usage Description

APPDelegate中请求权限

if (@available(iOS 10.0, *)) {
        [SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
            NSLog(@"status %@", status == SFSpeechRecognizerAuthorizationStatusAuthorized ? @"授权成功" : @"授权失败");
        }];
    } else {

    }

PBSpeechRecognizer.h

NS_ASSUME_NONNULL_BEGIN
@protocol PBSpeechRecognizerProtocol <NSObject>
@optional
- (void)recognitionSuccess:(NSString *)result;
- (void)recognitionFail:(NSString *)result;
@end
@interface PBSpeechRecognizer : NSObject
@property(nonatomic,weak) id<PBSpeechRecognizerProtocol> delegate;
- (void)startR;
- (void)stopR;
@end

NS_ASSUME_NONNULL_END

PBSpeechRecognizer.m

#import "PBSpeechRecognizer.h"
#import <Speech/Speech.h>
API_AVAILABLE(ios(10.0))
@interface PBSpeechRecognizer()
@property (nonatomic, strong) AVAudioEngine *audioEngine;
@property (nonatomic, strong) SFSpeechRecognizer *speechRecognizer;
@property (nonatomic, strong) SFSpeechAudioBufferRecognitionRequest *recognitionRequest;
@end
@implementation PBSpeechRecognizer

- (void)startR {
    if (!self.speechRecognizer) {
        // 设置语言
        NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
        if (@available(iOS 10.0, *)) {
            self.speechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:locale];
        } else {
            // Fallback on earlier versions
        }
    }
    if (!self.audioEngine) {
        self.audioEngine = [[AVAudioEngine alloc] init];
    }
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if (@available(iOS 10.0, *)) {
        [audioSession setCategory:AVAudioSessionCategoryRecord mode:AVAudioSessionModeMeasurement options:AVAudioSessionCategoryOptionDuckOthers error:nil];
    } else {
        // Fallback on earlier versions
    }
    [audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
    if (self.recognitionRequest) {
        [self.recognitionRequest endAudio];
        self.recognitionRequest = nil;
    }
    if (@available(iOS 10.0, *)) {
        self.recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
    } else {
        // Fallback on earlier versions
    }
    self.recognitionRequest.shouldReportPartialResults = YES; // 实时翻译
    if (@available(iOS 10.0, *)) {
        [self.speechRecognizer recognitionTaskWithRequest:self.recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
            if (result.isFinal) {
                NSLog(@"is final: %d  result: %@", result.isFinal, result.bestTranscription.formattedString);
                if ([self.delegate respondsToSelector:@selector(recognitionSuccess:)]) {
                    [self.delegate recognitionSuccess:result.bestTranscription.formattedString];
                }
            }else {
                if ([self.delegate respondsToSelector:@selector(recognitionFail:)]) {
//                    [self.delegate recognitionFail:error.domain];
                }
            }
        }];
    } else {
        // Fallback on earlier versions
    }
    AVAudioFormat *recordingFormat = [[self.audioEngine inputNode] outputFormatForBus:0];
    [[self.audioEngine inputNode] installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
        [self.recognitionRequest appendAudioPCMBuffer:buffer];
    }];
    [self.audioEngine prepare];
    [self.audioEngine startAndReturnError:nil];
}
- (void)stopR {
    [[self.audioEngine inputNode] removeTapOnBus:0];
    [self.audioEngine stop];
    [self.recognitionRequest endAudio];
    self.recognitionRequest = nil;
}
@end

在使用的控制器, 直接引用并调用.

_speech = [[PBSpeechRecognizer alloc] init];
_speech.delegate = self;
/// 语音开始按钮
[_soundButton addTarget:self action:@selector(startRecording:) forControlEvents:UIControlEventTouchDown];
    [_soundButton addTarget:self action:@selector(stopRecording:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
- (void)startRecording:(UIButton *)obj {
    [_speech startR];
}
- (void)stopRecording:(UIButton *)obj {
    [_speech stopR];
}
- (void)recognitionSuccess:(NSString *)result {
    [MBProgressHUD showSuccessMessage:result];
}

结果如图
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sinat_30162391/article/details/83097007
今日推荐