Advertisement
retesere20

Untitled

Feb 20th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. async Task<object> Start(int seconds)
  2. {
  3. if (NAudio.Wave.WaveIn.DeviceCount < 1) { MessageBox.Show("No microphone!"); return -1; }
  4.  
  5. var streamingCall = SpeechClient.Create().StreamingRecognize();
  6. await streamingCall.WriteAsync(
  7. new StreamingRecognizeRequest()
  8. {
  9. StreamingConfig = new StreamingRecognitionConfig()
  10. {
  11. Config = new RecognitionConfig()
  12. {
  13. Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
  14. MaxAlternatives = 1,
  15. SampleRateHertz = 16000,
  16. LanguageCode = "en-US",
  17. },
  18. InterimResults = true,
  19. SingleUtterance = false
  20. }
  21. }
  22. );
  23.  
  24. // Print responses as they arrive
  25. Task prinResp = Task.Run(async () =>
  26. {
  27. while (await streamingCall.ResponseStream.MoveNext(default(CancellationToken)))
  28. {
  29. foreach (var result in streamingCall.ResponseStream.Current.Results)
  30. {
  31. MessageBox.Show(result.Alternatives[0].Transcript.ToString());
  32. }
  33. }
  34. });
  35.  
  36. // Read from the microphone and stream to API.
  37. object writeLock = new object();
  38. bool writeMore = true;
  39. var waveIn = new NAudio.Wave.WaveInEvent();
  40. waveIn.DeviceNumber = 0;
  41. waveIn.WaveFormat = new NAudio.Wave.WaveFormat(16000, 1);
  42. waveIn.DataAvailable +=
  43. (object sender, NAudio.Wave.WaveInEventArgs args) =>
  44. {
  45. lock (writeLock)
  46. {
  47. if (!writeMore) return;
  48. streamingCall.WriteAsync( new StreamingRecognizeRequest() { AudioContent = Google.Protobuf.ByteString.CopyFrom(args.Buffer, 0, args.BytesRecorded) }).Wait();
  49. }
  50. };
  51. waveIn.StartRecording();
  52. MessageBox.Show("Speak now.");
  53. await Task.Delay(TimeSpan.FromSeconds(seconds));
  54. waveIn.StopRecording();
  55. lock (writeLock) writeMore = false;
  56. await streamingCall.WriteCompleteAsync();
  57. await prinResp; //wait before printout finished
  58. return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement