Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- async Task<object> Start(int seconds)
- {
- if (NAudio.Wave.WaveIn.DeviceCount < 1) { MessageBox.Show("No microphone!"); return -1; }
- var streamingCall = SpeechClient.Create().StreamingRecognize();
- await streamingCall.WriteAsync(
- new StreamingRecognizeRequest()
- {
- StreamingConfig = new StreamingRecognitionConfig()
- {
- Config = new RecognitionConfig()
- {
- Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
- MaxAlternatives = 1,
- SampleRateHertz = 16000,
- LanguageCode = "en-US",
- },
- InterimResults = true,
- SingleUtterance = false
- }
- }
- );
- // Print responses as they arrive
- Task prinResp = Task.Run(async () =>
- {
- while (await streamingCall.ResponseStream.MoveNext(default(CancellationToken)))
- {
- foreach (var result in streamingCall.ResponseStream.Current.Results)
- {
- MessageBox.Show(result.Alternatives[0].Transcript.ToString());
- }
- }
- });
- // Read from the microphone and stream to API.
- object writeLock = new object();
- bool writeMore = true;
- var waveIn = new NAudio.Wave.WaveInEvent();
- waveIn.DeviceNumber = 0;
- waveIn.WaveFormat = new NAudio.Wave.WaveFormat(16000, 1);
- waveIn.DataAvailable +=
- (object sender, NAudio.Wave.WaveInEventArgs args) =>
- {
- lock (writeLock)
- {
- if (!writeMore) return;
- streamingCall.WriteAsync( new StreamingRecognizeRequest() { AudioContent = Google.Protobuf.ByteString.CopyFrom(args.Buffer, 0, args.BytesRecorded) }).Wait();
- }
- };
- waveIn.StartRecording();
- MessageBox.Show("Speak now.");
- await Task.Delay(TimeSpan.FromSeconds(seconds));
- waveIn.StopRecording();
- lock (writeLock) writeMore = false;
- await streamingCall.WriteCompleteAsync();
- await prinResp; //wait before printout finished
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement