retesere20

Untitled

Mar 4th, 2018
37
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public async Task<object> StreamingMicRecognizeAsync(int seconds)
  2. {
  3. streamingCall = SpeechClient.Create().StreamingRecognize();
  4. await streamingCall.WriteAsync(
  5. new StreamingRecognizeRequest()
  6. {
  7. StreamingConfig = new StreamingRecognitionConfig()
  8. {
  9. Config = new RecognitionConfig()
  10. {
  11. Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
  12. SampleRateHertz = 16000,
  13. LanguageCode = "en-US"
  14. },
  15. InterimResults = true,
  16. SingleUtterance = false
  17. }
  18. }
  19. );
  20.  
  21. Task prinResp = Task.Run(async () =>
  22. {
  23. while (isActive && await streamingCall.ResponseStream.MoveNext(default(CancellationToken)))
  24. {
  25. foreach (var result in streamingCall.ResponseStream.Current.Results)
  26. {
  27. MessageBox.Show(result.Alternatives[0].Transcript.ToString());
  28. }
  29. }
  30. });
  31.  
  32. // Read from the microphone and stream to API.
  33. object writeLock = new object();
  34. bool writeMore = true;
  35. waveIn = new NAudio.Wave.WaveInEvent();
  36. waveIn.DeviceNumber = 0;
  37. waveIn.WaveFormat = new NAudio.Wave.WaveFormat(16000, 1);
  38. waveIn.DataAvailable +=
  39. (object sender, NAudio.Wave.WaveInEventArgs args) =>
  40. {
  41. lock (writeLock)
  42. {
  43. if (!writeMore || !isActive) return;
  44. try
  45. {
  46. streamingCall.WriteAsync(
  47. new StreamingRecognizeRequest()
  48. {
  49. AudioContent = Google.Protobuf.ByteString.CopyFrom(args.Buffer, 0, args.BytesRecorded)
  50. }).Wait();
  51. }
  52. catch (Exception e) { my.message(e.Message); }
  53. }
  54. };
  55.  
  56. waveIn.StartRecording();
  57. await Task.Delay(TimeSpan.FromSeconds(180*60));
  58. waveIn.StopRecording();
  59. lock (writeLock) writeMore = false;
  60. await streamingCall.WriteCompleteAsync();
  61. await prinResp;
  62. return 0;
  63. }
RAW Paste Data