ios10 語音轉文字

2016年的WWDC大會上,蘋果公司公佈了一下新的框架 語音轉文字。Speech framework,而後就本身感受挺有意思就研究了一下。

1.首先你要在xcode8裏去建立一個工程。而後添加speech頭文件。

#import <Speech/Speech.h>

2.建立一個按鈕用來啓動,關閉錄音。建立一個textfield來顯示轉換好的文字。建立一個語音控制器。建立一個語音識別請求。建立一個管理語音任務管理器。還有一個錄音設備。而且給管理器添加代理方法

@interface ViewController ()<SFSpeechRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UIButton *recordingBtn;
@property (weak, nonatomic) IBOutlet UILabel *titleLab;
@property (weak, nonatomic) IBOutlet UITextField *inPutTextField;
@property(nonatomic,strong)SFSpeechRecognizer * recognizer ;


//語音識別功能
@property(nonatomic,strong)SFSpeechAudioBufferRecognitionRequest * recognitionRequest ;
@property(nonatomic,strong)SFSpeechRecognitionTask * recognitionTask ;
@property(nonatomic,strong)AVAudioEngine * audioEngine ;

####3.將設備識別語音爲中文xcode

NSLocale *cale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh-CN"];
    self.recognizer = [[SFSpeechRecognizer alloc]initWithLocale:cale];
    self.recordingBtn.enabled = false;
     //設置代理
    self.recognizer.delegate = self;

####4.發送語音認證請求(首先要判斷設備是否支持語音識別功能)app

[SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
        bool isButtonEnabled = false;
        switch (status) {
            case SFSpeechRecognizerAuthorizationStatusAuthorized:
                isButtonEnabled = true;
                NSLog(@"能夠語音識別");
                break;
            case SFSpeechRecognizerAuthorizationStatusDenied:
                isButtonEnabled = false;
                NSLog(@"用戶被拒絕訪問語音識別");
                break;
            case SFSpeechRecognizerAuthorizationStatusRestricted:
                isButtonEnabled = false;
                NSLog(@"不能在該設備上進行語音識別");
                break;
            case SFSpeechRecognizerAuthorizationStatusNotDetermined:
                isButtonEnabled = false;
                NSLog(@"沒有受權語音識別");
                break;
            default:
                break;
        }
        self.recordingBtn.enabled = isButtonEnabled;
    }];

####5.建立錄音引擎。框架

self.audioEngine = [[AVAudioEngine alloc]init];

####6.建立按鈕點擊事件atom

- (void)BtnClick:(UIButton *)sender {
    if ([self.audioEngine isRunning]) {
        [self.audioEngine stop];
        [self.recognitionRequest endAudio];
        self.recordingBtn.enabled = YES;
        [self.recordingBtn setTitle:@"開始錄製" forState:UIControlStateNormal];
    }else{
        [self startRecording];
        [self.recordingBtn setTitle:@"中止錄製" forState:UIControlStateNormal];
    }  
}

####7.開始錄音代理

- (void)startRecording{
    if (self.recognitionTask) {
        [self.recognitionTask cancel];
        self.recognitionTask = nil;
    }
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    bool  audioBool = [audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
    bool  audioBool1= [audioSession setMode:AVAudioSessionModeMeasurement error:nil];
    bool  audioBool2= [audioSession setActive:true withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
    if (audioBool || audioBool1||  audioBool2) {
        NSLog(@"能夠使用");
    }else{
        NSLog(@"這裏說明有的功能不支持");
    }
    self.recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc]init];
    AVAudioInputNode *inputNode = self.audioEngine.inputNode;
    
    self.recognitionRequest.shouldReportPartialResults = true;
    
    //開始識別任務
    self.recognitionTask = [self.recognizer recognitionTaskWithRequest:self.recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
        bool isFinal = false;
        if (result) {
            self.inPutTextField.text = [[result bestTranscription] formattedString]; //語音轉文本
            isFinal = [result isFinal];
        }
        if (error || isFinal) {
            [self.audioEngine stop];
            [inputNode removeTapOnBus:0];
            self.recognitionRequest = nil;
            self.recognitionTask = nil;
            self.recordingBtn.enabled = true;
        }
    }];
    AVAudioFormat *recordingFormat = [inputNode outputFormatForBus:0];
    [inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
        [self.recognitionRequest appendAudioPCMBuffer:buffer];
    }];
    [self.audioEngine prepare];
    bool audioEngineBool = [self.audioEngine startAndReturnError:nil];
    NSLog(@"%d",audioEngineBool);
    self.inPutTextField.text = @"大妹砸。聊十塊錢的";
}

8.設置代理方法。

- (void)speechRecognizer:(SFSpeechRecognizer *)speechRecognizer availabilityDidChange:(BOOL)available{
    if (available) {
        self.recordingBtn.enabled = YES;
    }else{
    
        self.recordingBtn.enabled = NO;
    }
}
相關文章
相關標籤/搜索