如何播放 dialogflow 的输出音频(int 数组)

How to play the output audio from dialogflow (int array)

我正在使用 dialogflow 进行语音识别和意图,但是当我收到输出音频的响应时,我找不到播放音频响应的方法。音频响应​​以某种数组的格式出现。 JSON 对象如下所示(这是我要转换为音频的数据参数):

{
   "type":"Buffer",
   "data":[255,251,16,196,0,0,0,0,1,164,20,0,0,32,...]},
   "latency":2906,
   "fulfillmentMessages":["Here's your Adele playlist."],
   "parameters":
      {
         "any":[],
         "music-artist":["Adele"]},
         "success":true
      }
}

我已经尝试过将其转换为 ArrayBuffer 然后对其进行解码,但这似乎也不起作用

  playByteArray(byteArray) {
    var arrayBuffer = new ArrayBuffer(byteArray.length);
    var bufferView = new Uint8Array(arrayBuffer);
    for (let i = 0; i < byteArray.length; i++) {
      bufferView[i] = byteArray[i];
    }
    let context = new AudioContext();
    context.decodeAudioData(
      arrayBuffer,
      function(buffer) {
        this.play(buffer);
      }.bind(this)
    );
  }

  play(buf) {
    // Create a source node from the buffer
    let context = new AudioContext();
    var source = context.createBufferSource();
    source.buffer = buf;
    // Connect to the final output node (the speakers)
    source.connect(context.destination);
    // Play immediately
    source.start(0);
  }

编辑:这是我从 DialogFlow 返回的 JSON 示例: https://drive.google.com/open?id=1Y2UegyJ9BEwL6AR77Skly7prA4UalsNM

看来问题出在后端。我们有一些错误的配置: 请求中的 outputAudioConfig 应如下所示:

outputAudioConfig: {
      audioEncoding: `OUTPUT_AUDIO_ENCODING_LINEAR_16`,
      sampleRateHertz: 44100
    }

但音频编码设置为 "OUTPUT_AUDIO_ENCODING_MP3"

除此之外他们还添加了一个错误的参数:

 queryParams: {
      payload: structjson.jsonToStructProto({ source: "ACTIONS_ON_GOOGLE" }) // Let's pretend to be Google
    }

删除此参数后,我在问题中列出的代码有效。 感谢@Kolban 指出响应数组一开始就不正确。