欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue仿网易云音乐播放器界面的简单实现过程

程序员文章站 2022-04-21 09:55:22
由于工作项目的需要,需要使用到歌曲播放,参考多方资料,写了一个仿网易云音乐播放界面,能完整的实现音乐播放功能。前端简单的使用vue组件和audio标签实现了播放器界面,后端则是调用网易云的api获取对...

由于工作项目的需要,需要使用到歌曲播放,参考多方资料,写了一个仿网易云音乐播放界面,能完整的实现音乐播放功能。

vue仿网易云音乐播放器界面的简单实现过程

vue仿网易云音乐播放器界面的简单实现过程

前端简单的使用vue组件和audio标签实现了播放器界面,后端则是调用网易云的api获取对应的歌曲信息。

vue仿网易云音乐播放器界面的简单实现过程

 废话不多说上代码

歌曲播放界面(musicplay.vue)

<template>
  <div class="main-page">
    <audio :src="songinfo.url" id="music" autoplay="autoplay"></audio>
    <div
      class="background-flitter"
      :style="`background-image: url(${songinfo.cover})`"
    ></div>
    <div class="play-mini">
      <div class="progress-bar" @click="handleprogressclick" ref="track">
        <div
          class="progress-box"
          :style="{ width: audioprogresspercent }"
        ></div>
      </div>
      <div class="songinfo">
        <img class="poster" :src="songinfo.cover" alt="" />
        <!-- 歌名、歌手名 -->
        <div class="info">
          <p style="font-weight: 600; color: #fff;">{{ songinfo.name }}</p>
          <p style="font-size: 14px; color: #fff">{{ songinfo.artistsname }}</p>
        </div>
      </div>
      <div class="controls">
        <!-- 上一首提示 -->
        <tooltip content="上一首" theme="light" :delay="1500">
          <a href="javascript:;">
            <icon
              type="md-skip-backward"
              @click="skipback"
              size="26"
              color="white"
            />
          </a>
        </tooltip>
        <!-- 播放暂停 -->
        <tooltip content="播放暂停" theme="light" :delay="1500">
          <img
            @click="playmusic"
            class="status"
            v-show="!playing"
            src="@/assets/play_icon.png"
            alt=""
          />
          <img
            class="status"
            @click="playmusic"
            v-show="playing"
            src="@/assets/play-02.png"
            alt=""
          />
        </tooltip>
        <!-- 下一首提示 -->
        <tooltip content="下一首" theme="light" :delay="1500">
          <a href="javascript:;">
            <icon
              type="md-skip-forward"
              @click="skipforward"
              size="26"
              color="white"
            />
          </a>
        </tooltip>
      </div>
      <div class="right-botton">
        <div class="text-div"></div>
        <!-- 音量 -->
        <a href="javascript:;">
          <icon
            :type="volumetype"
            size="26"
            color="white"
            @click="volumechange"
          />
        </a>
        <div class="text-div"></div>
        <slider
          style="width: 80px; z-index: 99999"
          @on-input="changevolum"
          v-model="volume"
        ></slider>
        <div class="text-div"></div>
        <div class="text-div"></div>
        <div class="text-div"></div>
        <!-- 歌曲播放类型 -->
        <tooltip :content="showplaytype" theme="light" :delay="1500">
          <a href="javascript:;">
            <icon
              :custom="playstatus"
              @click="playtypechange"
              size="26"
              color="white"
            />
          </a>
        </tooltip>
        <div class="text-div"></div>
        <div class="text-div"></div>
        <div class="playlist">
          <!-- 播放列表 -->
          <tooltip content="列表" theme="light" :delay="1500">
            <a href="javascript:;">
              <icon
                custom="iconfont icon-bofangqi-xuanji"
                @click="drawer = true"
                size="36"
                color="white"
              />
            </a>
          </tooltip>
        </div>
      </div>
    </div>
    <div class="song-cover-lyric">
      <div class="disc-continer">
        <div class="poster" ref="rotate">
          <img :src="songinfo.cover" alt="" />
        </div>
        <div class="song-name">{{ songinfo.name }}</div>
        <div class="song-artistsname">{{ songinfo.artistsname }}</div>
      </div>
      <div class="lyric">
        <mscroll
          ref="lyric"
          :color="color"
          :colorlight="colorlight"
          :lineheight="lineheight"
          :paddingtop="paddingtop"
          :fontsize="fontsize"
          :lyricindex="lyricindex"
          :lyricslist="lyricinfo"
        ></mscroll>
      </div>
    </div>
    <drawer
      title="播放列表"
      placement="left"
      width="320"
      :closable="false"
      v-model="drawer"
    >
      <div class="list-container">
        <div
          class="songinfo"
          v-for="(item, index) in songlist"
          :key="index"
          @click="playlistmusic(index)"
        >
          <img :src="item.cover" alt="" />
          <div class="info">
            <div class="name">{{ item.name }}</div>
            <div class="singer">{{ item.artistsname }}</div>
          </div>
        </div>
      </div>
    </drawer>
  </div>
</template>
<script>
import { showmessage } from "../../publicmethod/publicmethods";
import mscroll from "./lyricscroll.vue";
import commonjs from "../../utils/timeconversion";
import axios from "axios";
export default {
  data() {
    return {
      volumenum: 80, //暂存的音量
      volumestatus: true, //音量图标的变化
      volumetype: "md-volume-up", //音量图标
      playstatus: "iconfont icon-xunhuanbofang", //播放类型图标
      playing: false,
      drawer: false,
      playindex: 0,
      songinfo: {},
      songlist: [],
      volume: 80, // 音量
      lyricinfo: [],
      playtype: 1, // 播放类型:1-列表循环,2-随机播放,3-单曲循环
      showplaytype: "列表循环",
      audioprogress: 0,
      thumbtranslatex: 0,
      lyricindex: 0,
      color: "#fff", //歌词默认颜色
      colorlight: "#40ce8f", //歌词高亮色
      fontsize: "16px", //歌词字体大小
      lineheight: "42", //每段行高
      paddingtop: "300px", //高亮歌词部分居中
    };
  },
  created() {},
  components: {
    mscroll,
  },
  computed: {
    audioprogresspercent() {
      return `${this.audioprogress * 100}%`;
    },
  },
  mounted() {
    const music = document.getelementbyid("music");
    if (this.$route.query.play) {
      this.clickplay();
    } else {
this.getsonglist();
    }
 
    if (this.playing) {
      // 播放中,点击则为暂停
      this.playing = false;
      this.$refs.rotate.style.animationplaystate = "paused";
      music.pause();
    } else {
      // 暂停中,点击则为播放
      this.playing = true;
      this.$refs.rotate.style.animationplaystate = "running";
      music.play();
    }
  },
  methods: {
    //音量变化
    volumechange() {
      if (this.volumestatus) {
        this.volumestatus = false;
        this.volumenum = this.volume;
        this.volume = 0;
        this.volumetype = "md-volume-off";
      } else {
        this.volumestatus = true;
        this.volume = this.volumenum;
        this.volumetype = "md-volume-up";
      }
    },
    //歌曲播放类型变化
    playtypechange() {
      if (this.playtype == 1) {
        this.playtype = 2;
        this.showplaytype = "随机播放";
        this.playstatus = "iconfont icon-suijibofang";
        return;
      }
      if (this.playtype == 2) {
        this.playtype = 3;
        this.showplaytype = "单曲循环";
        this.playstatus = "iconfont icon-danquxunhuan";
        return;
      }
      if (this.playtype == 3) {
        this.playtype = 1;
        this.showplaytype = "列表循环";
        this.playstatus = "iconfont icon-xunhuanbofang";
        return;
      }
    },
    clickplay() {
      this.audioinit();
      this.getmusiclist(this.songinfo.id);
      this.$refs.rotate.style.animationplaystate = "running";
      this.playing = true;
      settimeout(() => {
        music.play();
      }, 100);
    },
    getsonglist() {
      axios.get("/musiccontroller/getmusiclist").then(this.getsonglistinfo);
    },
    getsonglistinfo(res) {
      let mylist;
      if (res.code == "0000") {
        mylist = res.data;
      } else {
        console.log("没查到数据");
        mylist = [
          {
            artistsname: "房东的猫",
            cover:
              "https://p3.music.126.net/kkrcswkbrsd8guaohillxa==/109951166077317301.jpg",
            id: 1857630559,
            name: "new boy",
            url: "https://music.163.com/song/media/outer/url?id=1857630559.mp3",
            lyric:
              "\n[00:25.075]\n[00:25.189]是的我看见到处是阳光\n[00:29.156]快乐在城市上空飘扬\n[00:32.773]新世界来得像梦一样\n[00:36.689]让我暖洋洋\n[00:40.122]你的老怀表还在转吗\n[00:43.822]你的旧皮鞋还能穿吗\n[00:47.506]这儿有一支未来牌香烟\n[00:51.479]你不想尝尝吗\n[00:54.512]明天一早 我猜阳光会好\n[01:02.679]我要把自己打扫\n[01:05.896]把破旧的全部卖掉\n[01:09.212]哦这样多好 快来吧奔腾电脑\n[01:17.329]就让它们代替我来思考\n[01:27.229]穿新衣吧 剪新发型呀\n[01:31.347]轻松一下windows98\n[01:35.048]打扮漂亮 18岁是天堂\n[01:39.064]我们的生活甜得像糖\n[01:42.431]穿新衣吧 剪新发型呀\n[01:46.098]轻松一下windows98\n[01:49.914]以后的路不再会有痛苦\n[01:53.948]我们的未来该有多酷\n[02:12.481]是的我看见到处是阳光\n[02:16.164]快乐在城市上空飘扬\n[02:19.847]新世界来的像梦一样\n[02:23.748]让我暖洋洋\n[02:27.164]你的老怀表还在转吗\n[02:30.815]你的旧皮鞋还能穿吗\n[02:34.614]这儿有一支未来牌香烟\n[02:38.448]你不想尝尝吗\n[02:41.548]明天一早我猜阳光会好\n[02:49.898]我要把自己打扫\n[02:53.564]把破旧的全部卖掉\n[02:56.198]哦这样多好 快来吧奔腾电脑\n[03:04.598]就让它们代替我来思考\n[03:11.081]\n[03:11.414]穿新衣吧剪新发型呀\n[03:14.698]轻松一下windows98\n[03:18.264]打扮漂亮18岁是天堂\n[03:22.481]我们的生活甜得像糖\n[03:25.964]穿新衣吧剪新发型呀\n[03:29.515]轻松一下windows98\n[03:33.264]以后的路不再会有痛苦\n[03:37.681]我们的未来该有多酷",
          },
        ];
      }
      this.songlist = mylist;
      this.songinfo = this.songlist[0];
      this.getmusiclist(this.songinfo.id); //通过正在播放的歌曲id获取歌曲播放的url歌词信息
      this.audioinit();
    },
    audioinit() {
      let that = this;
      let progressl = this.$refs.track.offsetwidth; // 进度条总长
      music.addeventlistener("timeupdate", () => {
        // 当前播放时间
        let comparetime = music.currenttime;
        for (let i = 0; i < that.lyricinfo.length; i++) {
          if (comparetime > parseint(that.lyricinfo[i].time)) {
            const index = that.lyricinfo[i].index;
            if (i === parseint(index)) {
              that.lyricindex = i;
            }
          }
        }
        that.currenttime = commonjs.timetostring(music.currenttime);
        that.audioprogress = music.currenttime / music.duration;
        that.thumbtranslatex = (that.audioprogress * progressl).tofixed(3);
      });
      music.addeventlistener("ended", () => {
        switch (parseint(that.playtype)) {
          case 1: // 列表循环
            that.playindex =
              that.playindex + 1 >= that.songlist.length
                ? 0
                : that.playindex + 1;
            break;
          case 2: // 随机播放
            that.playindex = math.floor(math.random() * that.songlist.length);
            break;
          case 3: // 单曲循环
            break;
        }
        that.songinfo = that.songlist[that.playindex];
        this.getmusiclist(that.songinfo.id);
        settimeout(() => {
          this.$refs.rotate.style.animationplaystate = "running";
          music.play();
        }, 200);
      });
    },
    //播放与暂停
    playmusic() {
      if (this.playing) {
        // 播放中,点击则为暂停
        this.playing = false;
        this.$refs.rotate.style.animationplaystate = "paused";
        music.pause();
      } else {
        // 暂停中,点击则为播放
        this.playing = true;
        this.$refs.rotate.style.animationplaystate = "running";
        music.play();
      }
    },
    playlistmusic(index) {
      this.playindex = index;
      this.songinfo = this.songlist[this.playindex];
      this.getmusiclist(this.songinfo.id);
      this.playing = true;
      this.drawer = false;
      settimeout(() => {
        this.$refs.rotate.style.animationplaystate = "running";
        music.play();
      }, 200);
    },
    //点击进度条
    handleprogressclick(event) {
      let progressl = this.$refs.track.offsetwidth; // 进度条总长
      let clickx = event.offsetx;
      let time = (clickx / progressl).tofixed(2);
      this.setprogress(time);
    },
    setprogress(x) {
      music.currenttime = music.duration * x;
    },
    // 上一首
    skipback() {
      this.skipfn("skipback");
    },
    // 下一首
    skipforward() {
      this.skipfn("skipforward");
    },
    //上下首封装
    skipfn(type) {
      switch (parseint(this.playtype)) {
        case 2: // 随机播放
          this.playindex = math.floor(math.random() * this.songlist.length);
          break;
        default:
          if (type == "skipback") {
            this.playindex - 1 >= 0 ? this.playindex-- : 0;
          } else {
            this.playindex =
              this.playindex + 1 >= this.songlist.length
                ? this.songlist.length - 1
                : this.playindex + 1;
          }
          break;
      }
      this.songinfo = this.songlist[this.playindex];
      this.getmusiclist(this.songinfo.id);
      this.playing = true;
      settimeout(() => {
        this.$refs.rotate.style.animationplaystate = "running";
        music.play();
      }, 200);
    },
    //调节音量
    changevolum(c) {
      music.volume = c / 100;
      if (music.volume == 0) {
        this.volumetype = "md-volume-off";
      } else {
        this.volumetype = "md-volume-up";
      }
    },
    //获取歌曲播放的url信息
    getmusiclist(id) {
      let that = this;
      axios.get("/musiccontroller/getmusicurlinfo/" + id).then(function (res) {
        switch (res.code) {
          case "0000":
            that.songinfo.url = res.data.url;
            that.getlyriclist(res.data.lyric);
            break;
          case "1111":
            showmessage("warning", res.message);
            break;
        }
      });
    },
    getlyriclist(lrc) {
      let lyricsobjarr = [];
      const regnewline = /\n/;
      const linearr = lrc.split(regnewline); // 每行歌词的数组
      const regtime = /\[\d{2}:\d{2}.\d{2,3}\]/;
      linearr.foreach((item) => {
        if (item === "") return;
        const obj = {};
        const time = item.match(regtime);
 
        obj.lyric =
          item.split("]")[1].trim() === "" ? "" : item.split("]")[1].trim();
        obj.time = time
          ? commonjs.timetoseconds(time[0].slice(1, time[0].length - 1))
          : 0;
        obj.uid = math.random().tostring().slice(-6);
        if (obj.lyric === "") {
          console.log("这一行没有歌词");
        } else {
          lyricsobjarr.push(obj);
        }
      });
      this.lyricinfo = lyricsobjarr.map((item, index) => {
        item.index = index;
        return {
          ...item,
        };
      });
    },
  },
};
</script>
 
<style lang="less" scoped>
.main-page {
  width: 100%;
  height: 100%;
  position: absolute;
  background: rgba(15, 15, 15, 0.4);
  overflow: hidden;
  .background-flitter {
    position: absolute;
    z-index: 0;
    background-repeat: no-repeat;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-size: cover;
    background-position: 50%;
    filter: blur(8px);
    // margin: -20px;
    opacity: 0.7;
    overflow: hidden;
    box-sizing: border-box;
  }
  .play-mini {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 72px;
    // background: #fff;
    display: flex;
    align-items: center;
    padding: 6px 0;
    box-sizing: border-box;
    z-index: 10;
    .songinfo {
      min-width: 360px;
      max-width: 480px;
      position: relative;
      padding: 0 18px;
      box-sizing: border-box;
      display: flex;
      .poster {
        width: 52px;
        height: 52px;
        border-radius: 5px;
        margin-top: 4px;
        margin-right: 20px;
      }
      .info {
        min-width: 280px;
        height: 100%;
        line-height: 30px;
        font-size: 16px;
      }
    }
    .controls {
      width: 280px;
      height: 100%;
      display: flex;
      align-items: center;
      img {
        width: 40px;
        height: 40px;
        cursor: pointer;
      }
      .status {
        width: 40px;
        height: 40px;
        margin-left: 36px;
        margin-right: 36px;
        cursor: pointer;
      }
    }
    .progress-bar {
      position: absolute;
      z-index: 10;
      top: -5px;
      width: 100%;
      height: 5px;
      background: rgba(255, 255, 255, 0.5);
      cursor: pointer;
      .progress-box {
        height: 100%;
        background: #40ce8f;
        position: relative;
      }
    }
    .right-botton {
      position: relative;
      width: 420px;
      height: 100%;
      display: flex;
      align-items: center;
      .text-div {
        color: #fff;
        height: 100%;
        line-height: 60px;
        margin-left: 5px;
        margin-right: 5px;
      }
      .playlist {
        position: absolute;
        right: 0px;
      }
      a {
        color: #333;
      }
    }
  }
  .song-cover-lyric {
    position: relative;
    width: 100%;
    height: 100%;
    padding-bottom: 72px;
    box-sizing: border-box;
    display: flex;
    overflow: hidden;
    .disc-continer {
      width: 50%;
      height: 100%;
      position: relative;
      .poster {
        position: relative;
        width: 280px;
        height: 280px;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.3);
        left: 50%;
        top: 100px;
        margin-left: -140px;
        box-shadow: 0 0 0 12px rgba(255, 255, 255, 0.4);
        animation: animations1 12s linear infinite forwards;
        animation-play-state: paused;
        overflow: hidden;
        margin-bottom: 160px;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .song-name {
        width: 100%;
        height: 40px;
        text-align: center;
        font-size: 32px;
        font-weight: 600;
        color: #fff;
        line-height: 40px;
      }
      .song-artistsname {
        width: 100%;
        height: 40px;
        text-align: center;
        font-size: 28px;
        font-weight: 600;
        color: #fff;
        line-height: 40px;
        margin-top: 24px;
      }
      @keyframes animations1 {
        from {
          transform: rotate(0deg);
        }
        to {
          transform: rotate(360deg);
        }
      }
    }
    .lyric {
      width: 50%;
      height: 600px;
      position: relative;
      overflow: hidden;
    }
  }
}
</style>
<style lang="less">
.ivu-drawer-body {
  .list-container {
    width: 100%;
    height: 100%;
    overflow: auto;
    position: relative;
    .songinfo {
      width: 100%;
      height: 42px;
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      cursor: pointer;
      img {
        width: 36px;
        height: 36px;
        border-radius: 5px;
        margin-right: 12px;
      }
      .info {
        position: relative;
        width: 240px;
        height: 36px;
        line-height: 18px;
        .name {
          width: 100%;
          height: 18px;
          font-size: 14px;
          font-weight: 600;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
          line-height: 18px;
        }
        .singer {
          width: 100%;
          height: 18px;
          font-size: 12px;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
          line-height: 18px;
        }
      }
    }
  }
}
</style>

歌词部分(lyricscroll.vue)

<template>
  <!--歌词-->
  <div
    ref="musiclyric"
    class="music-lyric"
    :style="{ 'padding-top': paddingtop }"
  >
    <div class="music-lyric-items" :style="lyrictop">
      <template v-if="lyricslist.length > 0">
        <p
          v-for="(item, index) in lyricslist"
          :key="index"
          :data-index="index"
          ref="lyric"
          :style="{
            color: lyricindex === index ? colorlight : color,
            'font-size': fontsize,
          }"
        >
          {{ item.lyric }}
        </p>
      </template>
      <p style="color: #fff" v-else>歌词拼命加载中。。。。。</p>
    </div>
  </div>
</template>
 
<script>
const component_name = "scroll";
 
export default {
  name: component_name,
  props: {
    // 歌词列表
    lyricslist: {
      type: array,
      default: () => [],
    },
    // 当前歌词下标索引
    lyricindex: {
      type: number,
      default: 0,
    },
    // 歌词默认色
    color: {
      type: string,
      default: "#fff",
    },
    // 歌词高亮色
    colorlight: {
      type: string,
      default: "#40ce8f",
    },
    fontsize: {
      type: string,
      default: "16px",
    },
    lineheight: {
      type: string,
      default: "42",
    },
    paddingtop: {
      type: string,
      default: "300px",
    },
  },
  data() {
    return {
      top: 0, // 歌词居中
      //歌词list示例
      lyriclistdemo: [
        {
          index: 0,
          lyric: "作曲 : cmj",
          time: 0,
        },
        {
          index: 1,
          lyric: "作词 : 桃玖",
          time: 0.29,
        },
        {
          index: 2,
          lyric: "你听啊秋末的落叶",
          time: 0.89,
        },
        {
          index: 3,
          lyric: "你听它叹息着离别",
          time: 5.14,
        },
        {
          index: 4,
          lyric: "只剩我独自领略",
          time: 9.39,
        },
        {
          index: 5,
          lyric: "海与山 风和月",
          time: 13.14,
        },
      ],
    };
  },
  mounted() {},
  watch: {
    lyricindex(newval, oldval) {},
  },
  computed: {
    lyrictop() {
      return `transform :translate3d(0, ${(0 - this.lineheight) *
        (this.lyricindex - this.top)}px, 0);color: ${this.color};line-height: ${
        this.lineheight
      }px`;
    },
  },
  methods: {},
};
</script>
<style lang="less" scoped>
/*歌词部分*/
.music-lyric {
  padding-top: 300px;
  box-sizing: border-box;
  overflow: hidden;
  text-align: center;
  mask-image: linear-gradient(
    to bottom,
    rgba(255, 255, 255, 0) 0,
    rgba(255, 255, 255, 0.6) 5%,
    rgba(255, 255, 255, 1) 15%,
    rgba(255, 255, 255, 1) 85%,
    rgba(255, 255, 255, 0.6) 95%,
    rgba(255, 255, 255, 0) 100%
  );
  .music-lyric-items {
    text-align: center;
    font-size: 16px;
    color: #fff;
    transform: translate3d(0, 0, 0);
    transition: transform 0.6s ease-out;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    .on {
      color: #40ce8f;
    }
  }
}
</style>

时间转换的js(timeconversion.js)

/**
 * @author lyq
 * @time 2021年11月21日21:08:48
 *
 * 秒值转时分秒
 * @name timetostring
 * @example 秒值转时分秒
 * @param {string} seconds 秒
 */
const timetostring = (seconds) => {
    let param = parseint(seconds);
    let hh = "",
        mm = "",
        ss = "";
    if (param >= 0 && param < 60) {
        param < 10 ? (ss = "0" + param) : (ss = param);
        return "00:" + ss;
    } else if (param >= 60 && param < 3600) {
        mm = parseint(param / 60);
        mm < 10 ? (mm = "0" + mm) : mm;
        param - parseint(mm * 60) < 10 ?
            (ss = "0" + string(param - parseint(mm * 60))) :
            (ss = param - parseint(mm * 60));
        return mm + ":" + ss;
    }
}

基本前端代码都在这儿了,下面为后端的接口逻辑层代码

/**
 * @author : [liuyanqiang]
 * @version : [v1.0]
 * @classname : musicserviceimpl
 * @description : [描述说明该类的功能]
 * @createtime : [2021/11/16 14:28]
 * @updateuser : [liuyanqiang]
 * @updatetime : [2021/11/16 14:28]
 * @updateremark : [描述说明本次修改内容]
 */
@service
@slf4j
public class musicserviceimpl implements musicservice {
    @autowired
    private environment environment;
 
 
    /*
     * @version v1.0
     * title: getmusiclist
     * @author liuyanqiang
     * @description 获取热歌榜随机二十首音乐信息
     * @createtime  2021/11/16 14:32
     * @param []
     * @return java.util.map*/
    @override
    public list<map<string, object>> getmusiclist() {
        jsonarray resultobject = null;
        //拼接url发送对应的请求
        stringbuffer url = new stringbuffer();
        url.append("https://api.vvhan.com/api/rand.music?type=all&sort=热歌榜");
        //获取接口的返回值
        string body = httputils.sendget(url.tostring());
        resultobject = jsonobject.parsearray(body);
        list<map<string, object>> list = new arraylist<>();
        for (int i = 0; i < resultobject.size(); i++) {
            hashmap<string, object> map = new hashmap<string, object>();
            jsonobject jsonobject = resultobject.getjsonobject(i);
            map.put("cover", jsonobject.parseobject(jsonobject.get("album").tostring()).getstring("picurl"));
            map.put("artistsname", jsonobject.parsearray(jsonobject.get("artists").tostring()).getjsonobject(0).getstring("name"));
            map.put("name", jsonobject.getstring("name"));
            map.put("id", jsonobject.getstring("id"));
            list.add(map);
        }
        random random = new random();
        int num = random.nextint(179) % (179 - 0 + 1) + 0;
        list = list.sublist(num, num + 20);
        return list;
    }
 
    /*
     * @version v1.0
     * title: getmusicurlinfo
     * @author liuyanqiang
     * @description 获取音乐播放的url信息
     * @createtime  2021/11/19 9:22
     * @param [id——音乐id]
     * @return java.util.list<java.util.map<java.lang.string,java.lang.object>>*/
    @override
    public map<string, object> getmusicurlinfo(string id) {
        jsonobject resultobject = null;
        //拼接url发送对应的请求
        stringbuffer url = new stringbuffer();
        url.append("https://api.vvhan.com/api/music?id=" + id + "&type=song&media=netease");
        //获取接口的返回值
        string body = httputils.sendget(url.tostring());
        resultobject = jsonobject.parseobject(body);
        hashmap<string, object> map = new hashmap<string, object>();
        //判断第三方给的音乐url是否有效,无效则替换官方的url
        if(this.isvalid(resultobject.get("mp3url").tostring())){
            map.put("id", resultobject.get("song_id").tostring());
            map.put("name", resultobject.get("name"));
            map.put("artistsname", resultobject.get("author"));
            map.put("cover", resultobject.get("cover"));
            map.put("url", resultobject.get("mp3url"));
            map.put("lyric", this.getmusiclyricbyid(id) != null ? this.getmusiclyricbyid(id) : null);
        }
        else{
            map.put("id", id);
            map.put("url", "https://music.163.com/song/media/outer/url?id="+id+".mp3");
            map.put("lyric", this.getmusiclyricbyid(id) != null ? this.getmusiclyricbyid(id) : null);
        }
        return map;
    }
 
    /*
     * @version v1.0
     * title: isvalid
     * @author liuyanqiang
     * @description 判断链接是否有效
     * @createtime  2021/11/20 10:23
     * @param [strlink——输入链接]
     * @return boolean
     * */
    public boolean isvalid(string strlink) {
        url url;
        try {
            url = new url(strlink);
            httpurlconnection connt = (httpurlconnection) url.openconnection();
            connt.setrequestmethod("head");
            string strmessage = connt.getresponsemessage();
            if (strmessage.compareto("not found") == 0) {
                return false;
            }
            connt.disconnect();
        } catch (exception e) {
            return false;
        }
        return true;
    }
 
    /*
     * @version v1.0
     * title: getrandomfivemusic
     * @author liuyanqiang
     * @description 随机5首音乐,不能频繁调用,不然网易云接口回调异常
     * @createtime  2021/11/19 9:08
     * @param []
     * @return java.util.list<java.util.map<java.lang.string,java.lang.object>>*/
    @override
    public list<map<string, object>> getrandomfivemusic() {
        list<map<string, object>> list = new arraylist<>();
        for (int i = 0; i < 5; i++) {
            jsonobject resultobject = null;
            //拼接url发送对应的请求
            stringbuffer url = new stringbuffer();
            url.append("https://api.vvhan.com/api/rand.music?type=json&sort=热歌榜");
            //获取接口的返回值
            string body = httputils.sendget(url.tostring());
            resultobject = jsonobject.parseobject(body);
            jsonobject info = jsonobject.parseobject(resultobject.get("info").tostring());
            hashmap<string, object> map = new hashmap<string, object>();
            map.put("id", info.get("id").tostring());
            map.put("name", info.get("name"));
            map.put("artistsname", info.get("auther"));
            map.put("cover", info.get("picurl"));
            map.put("url", info.get("mp3url"));
            map.put("lyric", this.getmusiclyricbyid(info.get("id").tostring()) != null ? this.getmusiclyricbyid(info.get("id").tostring()) : null);
            list.add(map);
            log.info("调用成功" + i + "次");
        }
        return list;
    }
 
    /*
     * @version v1.0
     * title: getmusiclyricbyid
     * @author liuyanqiang
     * @description 获取歌词信息
     * @createtime  2021/11/16 19:23
     * @param [id——音乐id]
     * @return java.lang.string*/
    @override
    public string getmusiclyricbyid(string id) {
        try {
            jsonobject resultobject = null;
            //拼接url发送对应的请求
            stringbuffer url = new stringbuffer();
            url.append("https://music.163.com/api/song/media?id=" + id);
            //获取接口的返回值
            string body = httputils.sendget(url.tostring());
            resultobject = jsonobject.parseobject(body);
            if (resultobject.get("lyric").tostring() != null) {
                return resultobject.get("lyric").tostring();
            } else {
                return null;
            }
        } catch (exception e) {
            e.printstacktrace();
        }
        return null;
    }
}

总结

到此这篇关于vue仿网易云音乐播放器界面简单实现的文章就介绍到这了,更多相关vue网易云音乐播放器界面内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!