如何显示 Guzzle 响应 html 的流内容

how to show stream content from Guzzle response to html

我尝试使用 Guzzle 显示从 api 输出 audio/wav 的流响应。这就是我所做的

  $data = array(
          'input_text' => $request->input_text,
      );
      $url = "http://abc.or/tospeech";
      $client = new \GuzzleHttp\Client();
      $response = $client->post($url, [
          'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'],
          'body'    => json_encode($data)
      ]);

      $result = $response->getBody()->getContents();
return redirect('/home')->withInput()->with('result', $result);

从 $result 上面的代码中输出 null 但如果我将结果更改为

$result = (string)$response->getBody();

结果将如下所示

然后我尝试像这样html显示它

<audio id="source" class="form-control" controls>
       <source src="{{ session('result') }}" type="audio/wav">
       Your browser does not support the audio element.
</audio>

但什么也没发生。请帮助有人知道这件事。非常感谢。

假设您有这两条路线:

Route::get('/home', function (Request $request) {
    return view('index', [
        'input_text' => $request->input_text
    ]);
});

Route::get('/audio', function (Request $request) {
      $data = array(
          'input_text' => $request->input_text,
      );
      $url = "http://abc.or/tospeech";
      $client = new \GuzzleHttp\Client();
      $response = $client->post($url, [
          'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'],
          'body'    => json_encode($data)
      ]);

      $result = $response->getBody()->getContents();
      return response($result, 200, [
           'Content-Type' => 'audio/wav'
      ]);
})->name('stream');

那么您的视图将类似于:

<audio id="source" class="form-control" controls>
       <source src="{{ route('stream', [ 'input_text' => $input_text ]) }}" type="audio/wav">
       Your browser does not support the audio element.
</audio>

这里的想法是:

  1. 您最初的 /home 路线将保持不变(不确定之前的情况,这里我只是举一个例子)。
  2. 第二条路线将读取音频数据并将其作为响应发送。

这应该使音频元素在数据全部加载后播放数据。请注意,这不允许搜索音频,实际上会一次发送所有音频。如果你想支持搜索,你需要让你的路由支持 http range requests. There's at least one library 据说可以为 Laravel 提供支持,但这似乎已经过时,所以你可能需要进行额外的搜索。