private void _speechRecognizer_Results(object sender, ResultsEventArgs e)
 {
     try
     {
         SpeechRecognitionResult?.Invoke(this, new SpeechRecognitionEventArgs(e.Results.GetStringArrayList(SpeechRecognizer.ResultsRecognition).ToList()));
     }
     catch (Exception) { }
 }
示例#2
0
        public void StartSpeechRecognition()
        {
            StopSpeechRecognizer(false);
            StopAudio();
            _recognizerText = "";
            AVAudioSession.SharedInstance().SetActive(true, AVAudioSessionSetActiveOptions.NotifyOthersOnDeactivation);

            var request = new SFSpeechAudioBufferRecognitionRequest();

            request.ShouldReportPartialResults = true;

            var inputNode = engine.InputNode;

            _task = _recognizer.GetRecognitionTask(request, (result, error) =>
            {
                if (result != null)
                {
                    _recognizerText = result.BestTranscription.FormattedString;
                    if (_recognizerTimer == null)
                    {
                        _recognizerTimer = new Timer(RecognizeTimerElapsed, this, TimeSpan.FromSeconds(1), Timeout.InfiniteTimeSpan);
                    }
                    else
                    {
                        _recognizerTimer.Change(TimeSpan.FromSeconds(1), Timeout.InfiniteTimeSpan);
                    }
                    if (result.Final)
                    {
                        SpeechRecognitionResult?.Invoke(this, new SpeechRecognitionEventArgs(_recognizerText));
                    }
                    else
                    {
                        SpeechRecognitionPartialResult?.Invoke(this, new SpeechRecognitionEventArgs(_recognizerText));
                    }
                }
                if (error != null || result?.Final == true)
                {
                    StopSpeechRecognizer(false);
                }
            });

            var recordingFormat = inputNode.GetBusOutputFormat(0);

            inputNode.InstallTapOnBus(0, 1024, recordingFormat, (AVAudioPcmBuffer buffer, AVAudioTime when) =>
            {
                request.Append(buffer);
            });
            engine.Prepare();

            NSError engineError = null;

            if (engine.StartAndReturnError(out engineError))
            {
            }
        }
 private void _speechRecognizer_Error(object sender, ErrorEventArgs e)
 {
     //Evaluate e.Error?
     try
     {
         if (e.Error == SpeechRecognizerError.NoMatch || e.Error == SpeechRecognizerError.SpeechTimeout)
         {
             SpeechRecognitionResult?.Invoke(this, new SpeechRecognitionEventArgs(""));
         }
     }
     catch (Exception) { }
 }
示例#4
0
 private void RecognizeTimerElapsed(object state)
 {
     StopSpeechRecognizer(false);
     Xamarin.Forms.Device.BeginInvokeOnMainThread(() => SpeechRecognitionResult?.Invoke(this, new SpeechRecognitionEventArgs(_recognizerText)));//Necessary to run on UI thread
 }