1

根据https://cloud.google.com/speech/reference/rest/v1beta1/speech/asyncrecognize#authorization,我正在尝试将包含以下信息的发布请求发送到https://speech.googleapis.com/v1beta1 /speech:asyncrecognize在正文中:

{
  "config": {
  "encoding": 'FLAC',
  "sampleRate": 16000,
  },
  "audio": {
  "content": <a base64-encoded string representing an audio file>,
  },
}

我不知道如何在正文中设置这些参数。我们有 json 数据以及要放入正文的音频文件的二进制内容。这是我的代码:

        string mServerUrl = @"https://speech.googleapis.com/v1beta1/speech:asyncrecognize";

        MultipartFormDataContent content = new MultipartFormDataContent();
        content.Add(new StringContent("config"), "\"encoding\":\"FLAC\",\"sampleRate\":16000");
        content.Add(CreateFileContent("audio.flac"));

        HttpClient mHttpClient = new HttpClient();
        HttpResponseMessage mResponse = null;

        mResponse = await mHttpClient.PostAsync(mServerUrl, content);

        string responseBodyAsText = await mResponse.Content.ReadAsStringAsync();
4

1 回答 1

2

这个请求只是一个 JSON 格式的字符串。一旦你有一个 Json 格式的字符串,你可以使用它发送它

    HttpStringContent stringContent = new HttpStringContent(
            "{ \"firstName\": \"John\" }",
            UnicodeEncoding.Utf8,
            "application/json");

    HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.PostAsync(
            uri,
            stringContent);

要首先获取 JSON 字符串,您可以:

  1. 使用字符串生成器或 string.format 手动构建字符串
  2. 使用 Json.Net 库来构建它。

对于 audio.content 字段,您需要将文件转换为 base64 字符串

Public Function ConvertFileToBase64(ByVal fileName As String) As String
    Return Convert.ToBase64String(System.IO.File.ReadAllBytes(fileName))
End Function
于 2016-08-15T03:37:25.060 回答