Xamarin使用Plugin.AudioRecorder形成音频流并将其发送到Google Cloud Speech V1

时间:2019-05-08 11:46:38

标签: c# xamarin.forms audio-streaming speech-to-text google-speech-api

我正在Xamarin Forms项目中使用Plugin AudioRecorder,并尝试将音频流传输到Google Cloud Speech V1。如果使用基于事件的API方法并发送RecognitionAudio生成的RecognitionAudio.FromFile()对象,则该对象正常。

但是当我尝试通过将RecognitionAudio.FromStream()传递给方法recorder.GetAudioFileStream()时,它会捕获以下异常:

{System.NullReferenceException: Object reference not set to an instance of an object.
  at Plugin.AudioRecorder.AudioRecorderService.GetAudioFileStream () [0x00000] in C:\Repos\libs\Plugin.AudioRecorder\Plugin.AudioRecorder.Shared\AudioRecorderService.cs:135 
  at MyProject.Droid.GoogleSpeechToTextRecorder+<StreamingMicRecognizeAsync>d__1.MoveNext () [0x00053] in C:\Users\admin\Desktop\My Project\MyProject.Droid\GoogleSpeechToTextRecorder.cs:30 }

GoogleSpeechToTextRecorder.cs中的第30行在

AudioFunctions.WriteWavHeader(recorder.GetAudioFileStream(), 0, 48000, 24);

首先,我创建记录器,然后将WAV标头添加到流中。

recorder = new AudioRecorderService
{
    StopRecordingOnSilence = false,
    StopRecordingAfterTimeout = true,
    TotalAudioTimeout = TimeSpan.FromSeconds(59)
};

AudioFunctions.WriteWavHeader(recorder.GetAudioFileStream(), 0, 48000, 24);

await recorder.StartRecording();

// Credentials for Google

var channel = new Channel(SpeechClient.DefaultEndpoint.Host,
                          SpeechClient.DefaultEndpoint.Port,
                          credential.ToChannelCredentials());

var speech = SpeechClient.Create(channel, new SpeechSettings());

var responseThis = speech.Recognize(new RecognitionConfig()
                    {
                        Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
                        SampleRateHertz = 48000,
                        LanguageCode = "en",
                    }, RecognitionAudio.FromStream(recorder.GetAudioFileStream()));
foreach (var result in responseThis.Results)
{
    foreach (var alternative in result.Alternatives)
        Console.WriteLine(alternative.Transcript);
}

这是通过Google Cloud API进行双边语音文本交流的正确方法吗?我在做错什么?

0 个答案:

没有答案