我正在尝试将我的API转换为接受音频文件而不是字符串,但在查看之后我找不到合适的例子来说明这一点。
目前语音到文本服务在本地运行,但我想将其移动到服务器。 API调用我已经完成的wit.ai服务。剩下的就是让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;
}
}
}
答案 0 :(得分:0)
您可以使用IFormFile轻松地将文件上传到Asp.net核心web api,如下所示,您接受帖子操作中前一类型的参数
[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;
}
然后将其分配给控制器内的属性。
答案 1 :(得分:0)
感谢您的评论。
不完全是我正在寻找的东西,但这是我没有正确解释的错。以下是我发现的解决方案。
[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);
}