【问题标题】:Accepting audio file in api在 api 中接受音频文件
【发布时间】:2018-04-24 17:40:57
【问题描述】:

我正在尝试将我的 API 转换为接受音频文件而不是字符串,但在查看它之后我找不到合适的示例。

目前 Speech-To-Text 服务在本地运行,但我想将其移至服务器。我已经对 wit.ai 服务进行了 API 调用。剩下的就是让 API 接受一个音频文件(音频总是 .wav)

如果有人有一些建议,请告诉我我被困在这个问题上

[Produces("application/json")]
[Route("api")]
public class CommandApiController : Controller
{
    // constructor

    [HttpPost]
    public async Task<IActionResult> ProcessCommandAsync([FromBody]string command)
    {
        // Testing SpeechToText method
        string path = @"C:\Users\rickk\Desktop\SmartSpeaker\agenda.wav";
        // Overridden for now  
        command = await CovnvertSpeechToTextApiCall(new ByteArrayContent(System.IO.File.ReadAllBytes(path)));

        // Logic

    }


    async Task<string> CovnvertSpeechToTextApiCall(ByteArrayContent content)
    {
        var httpClient = new HttpClient();

        content.Headers.ContentType = MediaTypeHeaderValue.Parse("audio/wav");

        // Wit.ai server token
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
        var httpResponseMessage = await httpClient.PostAsync("https://api.wit.ai/speech", content);
        if (httpResponseMessage.IsSuccessStatusCode)
        {
            var response = await httpResponseMessage.Content.ReadAsStringAsync();
            var modeldata = Newtonsoft.Json.JsonConvert.DeserializeObject<Model.DeserializedJsonDataModel>(response);

            return modeldata._text;
        }
        else
        {
            return null;
        }
    }
}

【问题讨论】:

    标签: c# .net api .net-core


    【解决方案1】:

    您可以使用 IFormFile 轻松地将文件上传到 Asp.net 核心 web api,如下所示,您在 post 操作中接受上一个类型的参数

        [HttpPost]
        public async Task<IActionResult> UploadAudioFile(IFormFile file)
        {
            /* 
             * the content types of Wav are many
             * audio/wave
             * audio/wav
             * audio/x-wav
             * audio/x-pn-wav
             * see "https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types"
            */
            if (file.ContentType != "audio/wave")
            {
                return BadRequest("Wrong file type");
            }
            var uploads = Path.Combine(HostingEnvironment.WebRootPath, "uploads");//uploads where you want to save data inside wwwroot
            var filePath = Path.Combine(uploads, file.FileName);
            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }
            return Ok("File uploaded successfully");
        }
    

    您需要使用依赖注入在控制器构造函数中请求 IHostingEnvironment 对象,如下所示:

    public FileController(IHostingEnvironment hostingEnvironment)
        {
            HostingEnvironment = hostingEnvironment;
        }
    

    然后将其分配给控制器内的属性。

    除此之外,不要忘记将来自客户端的请求以 Multipart 形式发送,如下所示(示例):

    【讨论】:

      【解决方案2】:

      感谢您的评论。

      不完全是我想要的,但这是我没有正确解释的错。这是我找到的解决方案。

          [Produces("application/json")]
          [Route("api/audio")]
          [HttpPost]
          public async Task<IActionResult> ProcessCommandAsync([FromForm]IFormFile command)
          {  
              if(command.ContentType != "audio/wav" && command.ContentType != "audio/wave" || command.Length < 1)
              {
                  return BadRequest();
              }
              var text = await CovnvertSpeechToTextApiCall(ConvertToByteArrayContent(command));
      
              return Ok(FormulateResponse(text));
          }
      
      
          private ByteArrayContent ConvertToByteArrayContent(IFormFile audofile)
          {
              byte[] data;
      
              using (var br = new BinaryReader(audofile.OpenReadStream()))
              {
                  data = br.ReadBytes((int) audofile.OpenReadStream().Length);
              }
      
              return new ByteArrayContent(data);
          }
      

      【讨论】:

      • 感谢您的帖子。我有 2 个问题: 1. 我有错误“找不到类型或命名空间名称‘模型’”,是 Speech-To-Text 模型吗?如果我想用我的模型替换这个模型并调用我的 API,我应该怎么做? 2. 如何将“.wav”文件传递给 ProcessCommandAsync?我有一个错误“无法从'字符串'转换为'Microsoft.AspNetCore.Http.IFormFile'”谢谢。
      猜你喜欢
      • 1970-01-01
      • 2015-10-23
      • 2020-07-06
      • 2012-09-23
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 2018-07-31
      相关资源
      最近更新 更多