<template>
  <view v-if="message.messageType===MessageType.voice" class="main">
    <view @tap="handleAudio(message)">
      <text>{{ message.extend.time }}"</text>
      <view class="sound" :class="showSpinner?'active':''">
        <text class="cuIcon-sound text-xxl"></text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import {ref} from 'vue'
import MessageType from "@/utils/MessageType";
import type Message from "@/mode/Message";

const Audio = ref(uni.createInnerAudioContext());
const showSpinner = ref(false);

interface Props<T> {
  message: T
}

defineProps<Props<Message>>()
//控制播放还是暂停音频文件
const handleAudio = (item: Message) => {
  Audio.value.paused ? playAudio(item) : stopAudio();
}
//播放音频
const playAudio = (item: Message) => {
  if (item.extend?.url) {
    showSpinner.value = true;
    Audio.value.src = item.extend?.url
    Audio.value.play();
    Audio.value.onEnded(() => {
      showSpinner.value = false;
    })

    Audio.value.onStop(() => {
      showSpinner.value = false;
    })
  }
}
//停止音频
const stopAudio = () => {
  Audio.value.src = '';
  Audio.value.stop();
}
</script>

<style scoped>
/* 创建名为rotate的关键帧 */
@keyframes rotate {
  0% {
    transform: scale(1, 1);
  }
  50% {
    transform: scale(1.2, 1.2);
  }
  100% {
    transform: scale(1, 1);
  }
}

.sound {
  display: inline-flex;
  width: 1.25rem;
  height: 1.25rem;

  transform-origin: center;
  justify-content: center;
  align-items: center;
}

.active {
  animation-name: rotate;
  animation-duration: 0.5s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  color: #1cbbb4;
}


</style>
