C# 使用C语言的Google语音识别REST API出现错误请求#

C# 使用C语言的Google语音识别REST API出现错误请求#,c#,json,rest,unity3d,google-speech-api,C#,Json,Rest,Unity3d,Google Speech Api,我想使用C#中的Google语音识别API Rest。我之所以想使用API Rest而不是客户端库,是因为我想使用Unity3D,而它目前不支持客户端库 我使用HttpClient进行连接,使用Newtonsoft Json对Json进行序列化(我现在正在使用windows窗体,当它在Winforms中工作时,我将使用Unity) 我总是收到来自Google的错误请求响应,它没有给出更多细节,但我注意到,如果我将API键值更改为无效值,我会得到相同的结果 这是我的密码: 课程包括: class

我想使用C#中的Google语音识别API Rest。我之所以想使用API Rest而不是客户端库,是因为我想使用Unity3D,而它目前不支持客户端库

我使用HttpClient进行连接,使用Newtonsoft Json对Json进行序列化(我现在正在使用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;
        }

    }
}
我得到的是:

    {
      "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
    }

我知道我的代码可能不是最优雅的,但现在我只想从谷歌API得到一个好的响应。有什么线索吗?

我已经解决了这个问题

问题是我使用的是2声道音频文件,而谷歌语音API目前只接受单声道音频

因此,问题中的代码适用于单声道音频,可能对某些人有用


谢谢

首先,不要使用
.Result
阻塞异步。如果无法使代码始终保持异步,那么请使用同步API,如
HttpWebRequest
。但是,为了解决您的问题,您发送的json是什么?我怀疑序列化
这个
是你想要的。不要使用
ref
,使用
out
我想说,创建一个事件并用api响应调用它会更优雅。不用“ref”或“out”参数Shello,谢谢你的回复,我会发布我发送的json和我收到的json。我需要调用是同步的,我将尝试使用HttpWebRequest,但我想我会得到相同的结果。托拜厄斯:我想如果我想让它异步,事件会发生,但我希望它是同步的。
{  
       "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
    }