<template>
    <div class="MusicComponents" >
        <div class="musicbox">
    <!-- 播放 -->
     <div class="play" v-if="audioPlayShow" @click="audioState">
      <img :src="MusicOn"/>
    </div>
    <!-- 暂停-->
    <div class="play" v-else>
      <img :src="MusicOff" @click="audioState">
    </div>

    <audio ref="player" :src="audioHttp"></audio>
        </div>

    </div>
</template>
<script>
import MusicOn from "../common/icon/yinyueon.png";
import MusicOff from "../common/icon/yinyueoff.png";
export default {
     data() {
    return {
      MusicOn,
      MusicOff,
      audioPlayShow: true,
      cTime: "00:00", // 已播放时间
      dTime: "00:00", // 总播放时间
      audioHttp: "http://up.mcyt.net/?down/46426.mp3" // 音频链接
    };
  },
   mounted() {
    const music = this.$refs.player; // 音频所在对象
    music.addEventListener("canplay", () => {
      const musicTime = music.duration; // 获得音频时长
      const branch = Math.floor(musicTime / 60); // 计算音频分钟
      const second = Math.ceil(musicTime % 60); // 计算音频秒
      if (branch < 10 && second < 10) {
        // 四种情况判断音频总时间
        this.dTime = `0${branch}:0${second}`;
      } else if (branch < 10) {
        this.dTime = `0${branch}:${second}`;
      } else if (second < 10) {
        this.dTime = `${branch}:0${second}`;
      } else {
        this.dTime = `${branch}:${second}`;
      }
    });
  },
    methods: {
    // 点击播放暂停按钮时间
    audioState() {
      this.audioPlayShow = !this.audioPlayShow; // 更改播放暂停按钮状态
      const music = this.$refs.player; // 音频所在对象
      if (this.audioPlayShow) {
        music.play(); // 播放音乐
      } else {
        music.pause(); // 暂停音乐
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.MusicComponents{
    position: relative;
    height: 100%;
    width: 100%;

    .musicbox{
        position: absolute;
        top:1.27rem;
        right:0.09rem;
        width: 0.24rem;
        height: 0.24rem;
        border-radius: 50%;

        .play{
            width: 100%;
            height: 100%;

            img{
                width:100%;
                height: 100%;
            }
        }
    }
   
}
</style>


