Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

MicrosoftCognitiveSpeechService.cs 2.2 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  1. namespace SpeechToText.Services
  2. {
  3. using System;
  4. using System.IO;
  5. using System.Net.Http;
  6. using System.Threading.Tasks;
  7. using Newtonsoft.Json;
  8. public class MicrosoftCognitiveSpeechService
  9. {
  10. /// <summary>
  11. /// Gets text from an audio stream.
  12. /// </summary>
  13. /// <param name="audiostream"></param>
  14. /// <returns>Transcribed text. </returns>
  15. public async Task<string> GetTextFromAudioAsync(Stream audiostream)
  16. {
  17. var requestUri = @"https://speech.platform.bing.com/recognize?scenarios=smd&appid=D4D52672-91D7-4C74-8AD8-42B1D98141A5&locale=en-US&device.os=bot&form=BCSSTT&version=3.0&format=json&instanceid=565D69FF-E928-4B7E-87DA-9A750B96D9E3&requestid=" + Guid.NewGuid();
  18. using (var client = new HttpClient())
  19. {
  20. var token = Authentication.Instance.GetAccessToken();
  21. client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
  22. using (var binaryContent = new ByteArrayContent(StreamToBytes(audiostream)))
  23. {
  24. binaryContent.Headers.TryAddWithoutValidation("content-type", "audio/wav; codec=\"audio/pcm\"; samplerate=16000");
  25. var response = await client.PostAsync(requestUri, binaryContent);
  26. var responseString = await response.Content.ReadAsStringAsync();
  27. try
  28. {
  29. dynamic data = JsonConvert.DeserializeObject(responseString);
  30. return data.header.name;
  31. }
  32. catch (JsonReaderException ex)
  33. {
  34. throw new Exception(responseString, ex);
  35. }
  36. }
  37. }
  38. }
  39. /// <summary>
  40. /// Converts Stream into byte[].
  41. /// </summary>
  42. /// <param name="input">Input stream</param>
  43. /// <returns>Output byte[]</returns>
  44. private static byte[] StreamToBytes(Stream input)
  45. {
  46. using (MemoryStream ms = new MemoryStream())
  47. {
  48. input.CopyTo(ms);
  49. return ms.ToArray();
  50. }
  51. }
  52. }
  53. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...