尝试使用 Azure 语音识别和 Flutter 时出现错误 400

问题描述

我接到了在 Flutter 应用程序上使用 Azure 语音识别 API 的任务。该应用程序应该记录用户的声音并将其发送到 Azure API。我尝试使用我能找到的唯一 pub.dev 插件,但它不起作用,并且文档中没有 Flutter 示例。由于请求在 Postman 上返回 200 并且我能够使其在 Javascript 应用程序上运行,因此问题一定是我的 Flutter 应用程序,可能是请求中的某些内容,因为它返回代码 400(错误请求),表示请求包含无效数据。

下面的代码是我对 API 的请求。我用来获取字节的文件一个包含录制语音的 wav 文件

你能帮我吗?感谢关注。

      var bytes = file.readAsBytesSync();
      var response = await dio().post(
        "https://brazilsouth.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=pt-BR",data: bytes,options: Options(
            headers: {
              "Ocp-Apim-Subscription-Key": "subscriptionKey","Content-Type": "audio/wav"
            },);
      print(response.statusCode);

解决方法

尝试解决这个问题几天后,终于得到了成功的回应!

Future<dynamic> speechToText(File file) async {
    
    final bytes = file.readAsBytesSync();

    var headers = {
      'Ocp-Apim-Subscription-Key': 'b21db0729fc14cc7b6de72e1f44322dd','Content-Type': 'audio/wav'
    };

    var response;
    Map<String,dynamic> responseBody;
    var recognizedVoiceText;

    try {
      response = await http.post(
        "https://brazilsouth.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=pt-BR",body: bytes,headers: headers,);

      // The response body is a string that needs to be decoded as a json in order to get the extract the text.
      responseBody = jsonDecode(response.body);
      recognizedVoiceText = responseBody["DisplayText"];
    } catch (e) {
      print('Error: ${e.toString()}');
      recognizedVoiceText = "Something went wrong";
    }

    return recognizedVoiceText;
  }