播放ReadableStream格式二进制流音频

播放ReadableStream格式二进制流音频

接口返回中,body为ReadableStream格式的二进制流

<!DOCTYPE html>
<html>
  <head>
    <title>实时语音生成与播放</title>
  </head>
  <body>
    <h1>输入文本生成语音</h1>
    <textarea id="text-input" rows="4" cols="50"></textarea><br />
    <button onclick="generateAndPlayAudio()">生成并播放语音</button>
    <audio id="audio" controls></audio>
    <script>
      async function generateAndPlayAudio() {
        const text = document.getElementById("text-input").value;
        fetch("http://xxx.xx.xx.xxx:5000/generate_speech", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ text: text, port: 9880 }),
        })
          .then((response) => {
            console.log("response", response);
            if (response.ok) {
              const reader = response.body.getReader();
              let chunks = [];
              let totalLength = 0;
              const read = () => {
                return reader.read().then(({ done, value }) => {
                  if (done) {
                    return new Blob(chunks, { type: "audio/wav" });
                  }
                  chunks.push(value);
                  totalLength += value.length;
                  return read();
                });
              };
              return read();
            }
          })
          .then((audioBlob) => {
            const audioUrl = URL.createObjectURL(audioBlob);
            console.log("Audio URL:", audioUrl);
            const audioPlayer = document.getElementById("audio");
            audioPlayer.src = audioUrl;
            audioPlayer.play().catch((error) => {
              console.error("Error playing audio:", error);
            });
          });
      }
    </script>
  </body>
</html>

相关推荐

  1. 播放ReadableStream格式二进制音频

    2024-07-12 04:18:01       31 阅读
  2. vue 播放aac格式音频文件

    2024-07-12 04:18:01       23 阅读
  3. Audio音频资源播放

    2024-07-12 04:18:01       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 04:18:01       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 04:18:01       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 04:18:01       57 阅读
  4. Python语言-面向对象

    2024-07-12 04:18:01       68 阅读

热门阅读

  1. websocket学习

    2024-07-12 04:18:01       26 阅读
  2. Docker 安装字体文件

    2024-07-12 04:18:01       28 阅读
  3. 玩转springboot之xxxRunner接口使用

    2024-07-12 04:18:01       24 阅读
  4. Spring Security的Filter

    2024-07-12 04:18:01       27 阅读
  5. WVP后端项目文件结构

    2024-07-12 04:18:01       30 阅读
  6. 贪心算法-以学籍管理系统为例

    2024-07-12 04:18:01       26 阅读
  7. RISC-V主要指令集介绍及规则

    2024-07-12 04:18:01       27 阅读
  8. 【ChatGPT】全面解析 ChatGPT:从起源到未来

    2024-07-12 04:18:01       21 阅读
  9. 代码随想录算法训练营第9天

    2024-07-12 04:18:01       25 阅读
  10. 担心插座预留的不够用,家里装修留多少开关插座

    2024-07-12 04:18:01       19 阅读