<template>
  <div>
    <div class="model-viewer" ref="modelViewer"></div>
    <button @click="playTTS">播放语音</button>
  </div>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios";

const modelViewer = ref(null);

const playTTS = async () => {
  const ttsMessage =
    "替换为你想要播报的文本"; // 替换为你想要播报的文本

  try {
    const wgToken = `C1qziFGlIv3tnCQxcFaStrLuZOO2ZZXjN7FB_G0WlrOLjclfObbSaXAKzl4RWwQBf_0Zhsm0CoVvdVsYMD18iM_LJrxtn7LHJJQuF9UoUuF3fvqOwrG4EF6Z4GahtxtQ2oeaPQBBNKlgVW1xUW7tkhEdXWqzDHPA_I_91Lczk0PI4guhx1c88Hst4-HI8pdMbiUdEJzj3d3a2W06Fa0XA9Q0taAwaRd1k9jUrDVyj9GfS84_SIgJF4SPjWVfsraV79ieb_StgRcUwZjbscGPMlifnJD6F00wwNbxG7AuCHbl3EtMfSed1vuVx3AsizIckwzIVSVRpOGw72cdAMui-I6es9Ozj2ITzSa5KgyXEpX4qCHF1VcCM1wlHLQ_5hLnJIi4r8NsnJPsxMYrTw`;
    const res = await axios.post(
      `https://fls-ai-stg-sit.pingan.com.cn/openapi/ai/voice/tts/v2?channelId=ASP-TEST&sceneId=ASP-TEST&token=${wgToken}`,
      { sessionId: "N7FB_G0WlrOLjc", text: ttsMessage },
      {
        responseType: "arraybuffer",
        headers: {
          "X-Ai-TTS-Appid": "2b1317fb5b284b308dc90a6fdeae6c4e",
        },
      }
    );
    console.log(res.data);

    // 播放获取到的音频
    playAudio(res.data);
  } catch (error) {
    console.error("Error calling TTS API:", error);
  }
};

const playAudio = (audioData) => {
  const blob = new Blob([audioData], { type: "audio/wav" });
  const url = URL.createObjectURL(blob);
  const audio = new Audio(url);
  audio.onended = () => URL.revokeObjectURL(url);
  audio.onerror = (error) => console.error("Audio playback error:", error);
  audio
    .play()
    .then(() => console.log("Audio playing"))
    .catch((error) => console.error("Error playing audio:", error));
};
</script>

<style scoped>
.model-viewer {
  width: 100%;
  height: 400px;
}
</style>
