获取来自服务器的完整音频文件

huangapple go评论72阅读模式
英文:

Fetching full audio file from server

问题

I have a client and server set up. I'm currently fetching the file from my server and then streaming it to the client. I've tried to set it up so the audio doesn't start playing until it's fully loaded but I still get back partial audio. If I download the file on the browser, however, all of the audio is there. I'm implementing a TTS app so I can't preload the audio directly. How can I force the browser to not play until the full audio is able to be played through? Here's what I have so far.

const handleAudioLoaded = () => {
  console.log("Got here for the x'th time");
  const audioElement = document.getElementById(
    "audioplayer"
  ) as HTMLAudioElement;
  if (audioElement) audioElement.play();

{!loading && audio && (
    <ReactAudioPlayer
      id="audioplayer"
      src={`http://localhost:8000/audio/${audio}`}
      onCanPlayThrough={handleAudioLoaded}
      // onLoadedMetadata={handleAudioLoaded}
      preload="auto"
      controls
    />
  )}
}
英文:

I have a client and server set up. I'm currently fetching the file from my server and then streaming it to the client. I've tried to set it up so the audio doesn't start playing until it's fully loaded but I still get back partial audio. If I download the file on the browser, however, all of the audio is there. I'm implementing a TTS app so I can't preload the audio directly. How can I force the browser to not play until the full audio is able to be played through? Here's what I have so far.

const handleAudioLoaded = () =&gt; {
  console.log(&quot;Got here for the x&#39;th time&quot;);
  const audioElement = document.getElementById(
    &quot;audioplayer&quot;
  ) as HTMLAudioElement;
  if (audioElement) audioElement.play();

{!loading &amp;&amp; audio &amp;&amp; (
            &lt;ReactAudioPlayer
              id=&quot;audioplayer&quot;
              src={`http://localhost:8000/audio/${audio}`}
              onCanPlayThrough={handleAudioLoaded}
              // onLoadedMetadata={handleAudioLoaded}
              preload=&quot;auto&quot;
              controls
            /&gt;
          )}

答案1

得分: 2

你可以在你的情况下使用fetch下载音频,然后创建一个对象 URL 并分配给音频播放器。

fetch(`https://your-audio-location)
  .then(res => res.blob())
  .then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    const newAudioURL = objectURL;
  });
英文:

In your case, you can download the audio using fetch then create an object url and assign to the audio player.

fetch(`https://your-audio-location)
  .then(res =&gt; res.blob())
  .then((myBlob) =&gt; {
    const objectURL = URL.createObjectURL(myBlob);
    const newAudioURL = objectURL;
  });

huangapple
  • 本文由 发表于 2023年7月3日 10:40:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601566.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定