2016-11-27 28 views
0

我正在運行一個能夠正常工作的函數,並且我得到了正確的值,但是我正在解決如何從DI服務中獲取值(即帶有文本的字符串)返回到我的共享代碼的問題。當我在日誌中的函數類型,結果如下我得到正確的值:我如何從我的iOS Dependecy Service [Xamarin.Forms.iOS]中的任務<string>返回值?

RecognitionTask = SpeechRecognizer.GetRecognitionTask (LiveSpeechRequest, (SFSpeechRecognitionResult result, NSError err) => 
     { 
      thetextresult = result.BestTranscription.FormattedString; 
      System.Diagnostics.Debug.WriteLine(thetextresult); //I get the correct value 
     }); 

(如果我等待這上面的代碼可以在解決我的問題,也許?如果是的話我怎麼能等待從結果字符串)

我現在的問題是,這個代碼後,我與日誌工作再次,看看我是否可以在此功能後,再次達到日誌:

System.Diagnostics.Debug.WriteLine("Do I reach this?"); 

但我不能達到這個所以return thetextresult在函數的末尾沒有達到哪個意思在我的共享代碼中,我沒有得到任何回報。

這是代碼的外觀:在我的iOS DependecyService

功能:

 var node = AudioEngine.InputNode; 
     var recordingFormat = node.GetBusOutputFormat(0); 

     node.InstallTapOnBus(0, 1024, recordingFormat, (AVAudioPcmBuffer buffer, AVAudioTime when) => 
     { 
      LiveSpeechRequest.Append(buffer); 
     }); 

     AudioEngine.Prepare(); 
     NSError error; 
     AudioEngine.StartAndReturnError(out error); 

     RecognitionTask = SpeechRecognizer.GetRecognitionTask (LiveSpeechRequest, (SFSpeechRecognitionResult result, NSError err) => 
     { 
      thetextresult = result.BestTranscription.FormattedString; 
      System.Diagnostics.Debug.WriteLine(thetextresult); //value gets out correctly. 
     }); 


    } 

    System.Diagnostics.Debug.WriteLine("Do I reach this?"); //this does not get reached when i do the function. 
    return thetextresult; //which means that this is not returning the value 
} 

接口:

public interface ISoundToSpeak 
{ 
    Task<string> SpeechToTextAsync(); 
} 

我如何用我的contentpage,功能:

async Task <string>WaitForSpeech() 
    { 
     return await DependencyService.Get<ISoundToSpeak>().SpeechToTextAsync(); 
    } 

按鈕:

​​
+1

這不是自定義渲染器。這是一項DI服務。 – Jason

+0

@Jason啊好的!如果您爲平臺製作特定的代碼,就認爲您稱它爲渲染器!非常感謝信息:) –

+0

@Jason說到這個問題,你知道如何解決它嗎?我試圖「等待」thetextresult = result.BestTranscription.FormattedString;'我從'GetRecognitionTask'中獲得,但是因爲它是一個字符串,我無法等待結果。如果得到解決,也許這將解決問題 –

回答

1

你的功能StartRecord是異步,但我看不出它裏面的任何等待。 SpeechRecognizer.GetRecognitionTask是一個帶回調的任務。你應該能夠達到「我能達到這個嗎?」但是由於您不等到GetRecognitionTask完成,文本結果不會在那裏。您應該以某種方式等待RecognitionTask,或者不從函數返回textresult,而是從回調中調用您的共享代碼。

最後的工作是爲SpeechToTextAsync提供回調函數。

+0

如果你想更具體的修復,請發佈您的完整解決方案。 –

+0

已更新後的所有代碼 –

+0

你爲什麼稱它爲渲染器? –

相關問題