【问题标题】:how to show stream content from Guzzle response to html如何显示从 Guzzle 响应到 html 的流内容
【发布时间】:2021-08-31 08:45:10
【问题描述】:

我尝试使用 Guzzle 从 api 显示具有音频/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>

但是什么也没发生。请帮助是否有人知道这一点。我真的很感激。

【问题讨论】:

  • src 需要一个数据来源的 URL。在您的情况下,src 应该指向运行该代码的控制器操作,并且该代码应该直接返回数据,而不是使用会话中的数据重定向。
  • 但我的输出不是 URL 而是音频/wav。你知道如何解决这个问题吗?
  • 你需要把它分成两条不同的路线。一种是返回视图,一种是直接返回音频内容。然后在视图中,您的音频标签将具有其他操作的 url 的来源。
  • 你有路由如何显示音频/wav 的示例吗?因为我不知道如何获取音频/wav 内容。如果我显示它字符串,它总是为空或不为空

标签: php html laravel html5-audio guzzle


【解决方案1】:

假设你有这两条路线:

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 请求。据说有 at least one library 为 Laravel 提供支持,但这似乎已经过时,因此您可能需要进行额外的搜索。

【讨论】:

  • 非常感谢!对此,我真的非常感激。真的行。我不记得我是否可以回复。谢谢
猜你喜欢
  • 1970-01-01
  • 2013-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多