C#에서 Google 음성 인식 API 나머지를 사용하고 싶습니다. 클라이언트 라이브러리 대신 API Rest를 사용하려는 이유는 Unity3D를 사용하고자하며 현재 클라이언트 라이브러리를 지원하지 않기 때문입니다.C#에서 Google 음성 인식 REST API의 잘못된 요청 오류
HttpClient를 사용하여 연결하고 Newtonsoft Json을 사용하여 json을 serialize합니다 (지금은 Windows 양식으로 작업 중이며 Winforms에서 작동 할 때 Unity로 이동합니다).
항상 Google로부터 잘못된 요청 응답을 받지만 자세한 정보는 제공하지 않지만 API 키 값을 잘못된 값으로 변경하면 동일한 결과가 나타납니다.
클래스 : 여기
내 코드입니다class Speech
{
public RecognitionConfig config { get; set; }
public RecognitionAudio audio { get; set; }
public bool sendToApi(string baseUri, string url, ref string apiResponse)
{
try
{
HttpClient client = new HttpClient();
// Update port # in the following line.
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
//var speechJson = new JavaScriptSerializer().Serialize(certificado);
string speechJson = JsonConvert.SerializeObject(this);
var contenido = new StringContent(speechJson.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(url, contenido).Result;
if (response.IsSuccessStatusCode)
{
string responseJson = response.Content.ReadAsStringAsync().Result;
apiResponse = responseJson;
}
else
{
apiResponse = "ERROR " + JsonConvert.DeserializeObject(JsonConvert.SerializeObject(response));
}
return true;
}
catch (Exception e)
{
apiResponse = e.Message;
return false;
}
}
}
class RecognitionConfig
{
public string encoding { get; set; }
public int sampleRateHertz { get; set; }
public string languageCode { get; set; }
// public int maxAlternatives { get; set; }
// public bool profanityFilter { get; set; }
// public List<SpeechContext> speechContexts { get; set; }
// public bool enableWordTimeOffsets { get; set; }
}
class SpeechContext
{
public List<string> phrases { get; set; }
}
class RecognitionAudio
{
public string content { get; set; }
// public string uri { get; set; }
public bool setContentBase64FromAudio(string path)
{
try
{
FileStream fileStream = File.OpenRead(path);
MemoryStream memoryStream = new MemoryStream();
memoryStream.SetLength(fileStream.Length);
fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);
byte[] BA_AudioFile = memoryStream.GetBuffer();
this.content = System.Convert.ToBase64String(BA_AudioFile);
return true;
}
catch(Exception e)
{
return false;
}
}
}
호출 :
private void button1_Click(object sender, EventArgs e)
{
Speech speech = new Speech();
speech.config = new RecognitionConfig();
speech.audio = new RecognitionAudio();
speech.config.encoding = "FLAC";
speech.config.sampleRateHertz = 44100;
speech.config.languageCode = "en-US";
RecognitionAudio audio = new RecognitionAudio();
audio.setContentBase64FromAudio("C:\\Users\\Manena\\Downloads\\good-morning-google.flac");
speech.audio = audio;
string response = "";
speech.sendToApi("https://speech.googleapis.com/", "v1/speech:recognize?key=<mykey>", ref response);
textBox1.Text = response;
}
}
편집 : 여기에있는 JSON 내가 보내
{
"config":{
"encoding":"FLAC",
"sampleRateHertz":44100,
"languageCode":"en-US"
},
"audio":{
"content":"base64 audio"
}
}
그리고 내가받는 것 :
{
"Version": {
"Major": 1,
"Minor": 1,
"Build": -1,
"Revision": -1,
"MajorRevision": -1,
"MinorRevision": -1
},
"Content": {
"Headers": [
{
"Key": "Content-Type",
"Value": [
"application/json; charset=UTF-8"
]
}
]
},
"StatusCode": 400,
"ReasonPhrase": "Bad Request",
"Headers": [
{
"Key": "Vary",
"Value": [
"X-Origin",
"Referer",
"Origin",
"Accept-Encoding"
]
},
{
"Key": "X-XSS-Protection",
"Value": [
"1; mode=block"
]
},
{
"Key": "X-Frame-Options",
"Value": [
"SAMEORIGIN"
]
},
{
"Key": "X-Content-Type-Options",
"Value": [
"nosniff"
]
},
{
"Key": "Alt-Svc",
"Value": [
"hq=\":443\"; ma=2592000; quic=51303431; quic=51303339; quic=51303338; quic=51303337; quic=51303335,quic=\":443\"; ma=2592000; v=\"41,39,38,37,35\""
]
},
{
"Key": "Transfer-Encoding",
"Value": [
"chunked"
]
},
{
"Key": "Accept-Ranges",
"Value": [
"none"
]
},
{
"Key": "Cache-Control",
"Value": [
"private"
]
},
{
"Key": "Date",
"Value": [
"Sat, 30 Dec 2017 09:06:19 GMT"
]
},
{
"Key": "Server",
"Value": [
"ESF"
]
}
],
"RequestMessage": {
"Version": {
"Major": 1,
"Minor": 1,
"Build": -1,
"Revision": -1,
"MajorRevision": -1,
"MinorRevision": -1
},
"Content": {
"Headers": [
{
"Key": "Content-Type",
"Value": [
"application/json; charset=utf-8"
]
},
{
"Key": "Content-Length",
"Value": [
"106"
]
}
]
},
"Method": {
"Method": "POST"
},
"RequestUri": "https://speech.googleapis.com/v1/speech:recognize?key=mykey",
"Headers": [
{
"Key": "Accept",
"Value": [
"application/json"
]
}
],
"Properties": {}
},
"IsSuccessStatusCode": false
}
내 코드가 가장 우아하지 않지만 지금은 Google API에서 좋은 반응을 얻는 데에만 관심이 있다는 것을 알고 있습니다. 어떤 단서?
먼저
감사합니다 도움이 될 수 있습니다. 코드 비동기를 끝까지 만들 수 없다면'HttpWebRequest'와 같은 동기식 API를 사용하십시오. 그러나 문제를 해결하기 위해 보내는 json은 무엇입니까? 나는이 시리즈를 당신이 원하는대로 연재시키는 지 의심 스럽다. – Crowcoder
'ref'를 사용하지 말고'out'을 사용하십시오 – Amy
"ref"또는 "out"매개 변수를 사용하지 않고 이벤트를 생성하고 그 API 응답으로 호출하는 것이 더 멋지다고 말하고 싶습니다. –