forked from microsoft/BotBuilder-Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMicrosoftCognitiveSpeechService.cs
64 lines (58 loc) · 2.45 KB
/
MicrosoftCognitiveSpeechService.cs
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
59
60
61
62
63
64
namespace SpeechToText.Services
{
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
public class MicrosoftCognitiveSpeechService
{
/// <summary>
/// Gets text from an audio stream.
/// </summary>
/// <param name="audiostream"></param>
/// <returns>Transcribed text. </returns>
public async Task<string> GetTextFromAudioAsync(Stream audiostream)
{
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();
using (var client = new HttpClient())
{
var token = Authentication.Instance.GetAccessToken();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
using (var binaryContent = new ByteArrayContent(StreamToBytes(audiostream)))
{
binaryContent.Headers.TryAddWithoutValidation("content-type", "audio/wav; codec=\"audio/pcm\"; samplerate=16000");
var response = await client.PostAsync(requestUri, binaryContent);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
throw new HttpException((int)response.StatusCode, $"({response.StatusCode}) {response.ReasonPhrase}");
}
var responseString = await response.Content.ReadAsStringAsync();
try
{
dynamic data = JsonConvert.DeserializeObject(responseString);
return data.header.name;
}
catch (JsonReaderException ex)
{
throw new Exception(responseString, ex);
}
}
}
}
/// <summary>
/// Converts Stream into byte[].
/// </summary>
/// <param name="input">Input stream</param>
/// <returns>Output byte[]</returns>
private static byte[] StreamToBytes(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
}
}