• Vue2:网易云播放音乐并实现同步一次显示一行歌词


    一、项目数据API接口地址

    API地址:https://neteasecloudmusicapi.js.org/#/
    API文档说明地址:https://binaryify.github.io/NeteaseCloudMusicApi/#/

    二、实现播放页面效果

    在这里插入图片描述

    三、实现思路

    1、在路由跳转时携带ID参数发送ajax请求,根据id我们可以获取到歌曲的歌词

    2、对获取到的歌词进行切分并以key:value的形式放入到对象中,将每个时间段获得的歌词存起来方便页面渲染,其中key为时间

    3、同步一次显示一行歌词:如果当前播放的时间等于歌词的key值,那么就将当前歌词切换为这一句

    四、实现思路代码

    1、发送ajax请求获取歌词

    // 获取-并调用formatLyric方法, 处理歌词
    const lyrContent  = await getLyricByIdAPI({id:this.id});
    const lyricStr = lyrContent.data.lrc.lyric
    
    • 1
    • 2
    • 3

    我们可以得到的歌词的样式

    {
    lyric : "
    	[00:00.000] 作词 : 张军磊
    	[00:01.000] 作曲 : 李亚洲
    	[00:02.000] 编曲 : 李博
    	[00:03.000] 制作人 : 李亚洲
    	[00:29.98]风越过高高的山岗
    	......
    "
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2、 处理歌词格式

    可以看到我们的歌词是带时间的文本,需要对其切分,并以键值对的形式存放到对象中,将每个时间段的歌词以key:value的形式储存起来方便页面渲染

    ① 匹配所有[]字符串以及里面的一切内容, 返回数组

    let reg = /\[.+?\]/g 
    let timeArr = lyricStr.match(reg) 
    
    • 1
    • 2

    返回结果为["[00:00.000]", "[00:01.000]", ......]

    ② 按照[]拆分歌词字符串, 返回一个数组

    let contentArr = lyricStr.split(/\[.+?\]/).slice(1) 
    
    • 1

    返回的结果:[' 作词 : 张军磊\n', ' 作曲 : 李亚洲\n', ' 编曲 : 李博\n', ' 制作人 : 李亚洲\n', '风越过高高的山岗\n', ......]

    ③ 按照key:value的形式保存歌词对象(key是秒, value是显示的歌词)

    let lyricObj = {};
    timeArr.forEach((item, index) => {
    	// 拆分[00:00.000]这个格式字符串, 把分钟数字取出, 转换成秒
    	let ms = item.split(':')[0].split('')[2] * 60
    	// 拆分[00:00.000]这个格式字符串, 把十位的秒拿出来, 如果是0, 去拿下一位数字, 否则直接用2位的值
    	let ss = item.split(':')[1].split('.')[0].split('')[0] === '0' ? item.split(':')[1].split('.')[0].split('')[1] : item.split(':')[1].split('.')[0]
    	// 秒数作为key, 对应歌词作为value
    	lyricObj[ms + Number(ss)] = contentArr[index]
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    返回结果为:{0: ' 作词 : 张军磊\n', 1: ' 作曲 : 李亚洲\n', 2: ' 编曲 : 李博\n', 3: ' 制作人 : 李亚洲\n', 29: '风越过高高的山岗\n', ......}

    3、判定该显示哪句歌词

    将歌词数组进行遍历,如果当前歌曲播放时间等于歌词数组中歌词的时间,就将当前歌词换为这一句。

    timeupdate(){
        let curTime = Math.floor(this.$refs.audio.currentTime)
          // 避免空白出现
          if (this.lyric[curTime]) {
            this.curLyric = this.lyric[curTime]
            this.lastLy = this.curLyric
          } else {
            this.curLyric = this.lastLy
          }
      },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    4、代码部分

    html代码

     
    <div class="lrcContent">
      <p class="lrc">{{ curLyric }}p>
    div>
    
    
    <audio ref="audio" preload="true" :src="songInfo.url" @timeupdate="timeupdate">audio>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    css代码

    /* 歌词显示 */
    .scrollLrc {
      position: absolute;
      bottom: 280rpx;
      width: 640rpx;
      height: 120rpx;
      line-height: 120rpx;
      text-align: center;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    js代码

    data() {
       return {
         lyric: {}, // 歌词枚举对象(需要在js拿到歌词写代码处理后, 按照格式保存到这个对象)
         curLyric: '', // 当前显示哪句歌词
         lastLy: '' ,// 记录当前播放歌词
       }
     },
    async created(){
       // 获取-并调用formatLyric方法, 处理歌词
       const lyrContent  = await getLyricByIdAPI({id:this.id});
       const lyricStr = lyrContent.data.lrc.lyric
       this.lyric = this.formatLyric(lyricStr)
        // 初始化完毕先显示零秒歌词
       this.curLyric = this.lyric[0]
    },
    
    methods: {
       formatLyric(lyricStr) {
        // 可以看network观察歌词数据是一个大字符串, 进行拆分.
        let reg = /\[.+?\]/g //
        let timeArr = lyricStr.match(reg) // 匹配所有[]字符串以及里面的一切内容, 返回数组
        console.log(timeArr); // ["[00:00.000]", "[00:01.000]", ......]
        let contentArr = lyricStr.split(/\[.+?\]/).slice(1) // 按照[]拆分歌词字符串, 返回一个数组(下标为0位置元素不要,后面的留下所以截取)
        console.log(contentArr);
        let lyricObj = {} // 保存歌词的对象, key是秒, value是显示的歌词
        timeArr.forEach((item, index) => {
          // 拆分[00:00.000]这个格式字符串, 把分钟数字取出, 转换成秒
          let ms = item.split(':')[0].split('')[2] * 60
          // 拆分[00:00.000]这个格式字符串, 把十位的秒拿出来, 如果是0, 去拿下一位数字, 否则直接用2位的值
          let ss = item.split(':')[1].split('.')[0].split('')[0] === '0' ? item.split(':')[1].split('.')[0].split('')[1] : item.split(':')[1].split('.')[0]
          // 秒数作为key, 对应歌词作为value
          lyricObj[ms + Number(ss)] = contentArr[index]
        })
        // 返回得到的歌词对象(可以打印看看)
        console.log(lyricObj);
        return lyricObj
      },
    
      // 监听播放audio进度, 切换歌词显示
      timeupdate(){
        // console.log(this.$refs.audio.currentTime)
        let curTime = Math.floor(this.$refs.audio.currentTime)
         // 避免空白出现
        if (this.lyric[curTime]) {
          this.curLyric = this.lyric[curTime]
          this.lastLy = this.curLyric
        } else {
          this.curLyric = this.lastLy
        }
      },
    },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    五、整个页面完整代码

    paly/index.vue

    <template>
      <div class="play">
        
        <div
          class="song-bg" :style="`background-image: url();`">div>
        
        <div class="header">
          <van-icon name="arrow-left" size="20" class="left-incon" @click="$router.back()"/>
        div>
        
        <div class="song-wrapper">
          
          <div class="song-turn ani" :style="`animation-play-state:${playState ? 'running' : 'paused'}`">
            <div class="song-img">
              
              <img class="musicImg"  :src="musicInfo.al.picUrl"/>
            div>
          div>
          
          <div class="start-box" @click="audioStart">
            <span class="song-start" v-show="!playState">span>
          div>
          
          <div class="song-msg">
            
            <h2 class="m-song-h2">
              <span class="m-song-sname">{{ musicInfo.name }}-{{musicInfo.ar[0].name}}span
              >
            h2>
            
            <div class="needle" :style="`transform: rotate(${needleDeg});`">div>
            
            <div class="lrcContent">
              <p class="lrc">{{ curLyric }}p>
            div>
          div>
        div>
        
         <audio ref="audio" preload="true" :src="songInfo.url" @timeupdate="timeupdate">audio>
      div>
    template>
    
    <script>
    // 获取歌曲详情和 歌曲的歌词接口
    import { getSongByIdAPI, getLyricByIdAPI,getMusicByIdAPI } from '@/api'
    export default {
      name: 'play',
      data() {
        return {
          playState: false, // 音乐播放状态(true暂停, false播放)
          id: this.$route.query.id, // 上一页传过来的音乐id
          songInfo: {}, // 歌曲信息
          musicInfo:"", // 歌曲详情信息
          lyric: {}, // 歌词枚举对象(需要在js拿到歌词写代码处理后, 按照格式保存到这个对象)
          curLyric: '', // 当前显示哪句歌词
          lastLy: '' ,// 记录当前播放歌词
        }
      },
    
      computed: {
        needleDeg() { // 留声机-唱臂的位置属性
          return this.playState ? '-7deg' : '-38deg'
        }
      },
      async created(){
       // 获取歌曲详情, 和歌词方法
          const res = await getSongByIdAPI({id:this.id})
          this.songInfo = res.data.data[0];
    
          // 获取歌曲详情
          const musicInfo =await getMusicByIdAPI({ids:this.id});
          this.musicInfo = musicInfo.data.songs[0];
    
          // 获取-并调用formatLyric方法, 处理歌词
          const lyrContent  = await getLyricByIdAPI({id:this.id});
          const lyricStr = lyrContent.data.lrc.lyric
          this.lyric = this.formatLyric(lyricStr)
           // 初始化完毕先显示零秒歌词
          this.curLyric = this.lyric[0]
    
      },
      methods: {
         formatLyric(lyricStr) {
          // 可以看network观察歌词数据是一个大字符串, 进行拆分.
          let reg = /\[.+?\]/g //
          let timeArr = lyricStr.match(reg) // 匹配所有[]字符串以及里面的一切内容, 返回数组
          console.log(timeArr); // ["[00:00.000]", "[00:01.000]", ......]
          let contentArr = lyricStr.split(/\[.+?\]/).slice(1) // 按照[]拆分歌词字符串, 返回一个数组(下标为0位置元素不要,后面的留下所以截取)
          console.log(contentArr);
          let lyricObj = {} // 保存歌词的对象, key是秒, value是显示的歌词
          timeArr.forEach((item, index) => {
            // 拆分[00:00.000]这个格式字符串, 把分钟数字取出, 转换成秒
            let ms = item.split(':')[0].split('')[2] * 60
            // 拆分[00:00.000]这个格式字符串, 把十位的秒拿出来, 如果是0, 去拿下一位数字, 否则直接用2位的值
            let ss = item.split(':')[1].split('.')[0].split('')[0] === '0' ? item.split(':')[1].split('.')[0].split('')[1] : item.split(':')[1].split('.')[0]
            // 秒数作为key, 对应歌词作为value
            lyricObj[ms + Number(ss)] = contentArr[index]
          })
          // 返回得到的歌词对象(可以打印看看)
          console.log(lyricObj);
          return lyricObj
        },
    
        // 监听播放audio进度, 切换歌词显示
        timeupdate(){
          // console.log(this.$refs.audio.currentTime)
          let curTime = Math.floor(this.$refs.audio.currentTime)
           // 避免空白出现
          if (this.lyric[curTime]) {
            this.curLyric = this.lyric[curTime]
            this.lastLy = this.curLyric
          } else {
            this.curLyric = this.lastLy
          }
        },
    
        // 播放按钮 - 点击事件
        audioStart() {
          if (!this.playState) { // 如果状态为false
            this.$refs.audio.play() // 调用audio标签的内置方法play可以继续播放声音
          } else {
            this.$refs.audio.pause() // 暂停audio的播放
          }
          this.playState = !this.playState // 点击设置对立状态
        },
      },
    }
    script>
    
    <style scoped>
    /* 歌曲封面 */
    .musicImg {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      width: 100%;
      margin: auto;
      width: 370rpx;
      height: 370rpx;
      border-radius: 50%;
    }
    
    /* 歌词显示 */
    .scrollLrc {
      position: absolute;
      bottom: 280rpx;
      width: 640rpx;
      height: 120rpx;
      line-height: 120rpx;
      text-align: center;
    }
    
    
    .header {
      height: 50px;
    }
    .play {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 1000;
    }
    .song-bg {
      background-color: #161824;
      background-position: 50%;
      background-repeat: no-repeat;
      background-size: auto 100%;
      transform: scale(1.5);
      transform-origin: center;
      position: fixed;
      left: 0;
      right: 0;
      top: 0;
      height: 100%;
      overflow: hidden;
      z-index: 1;
      opacity: 1;
      filter: blur(25px); /*模糊背景 */
    }
    .song-bg::before{ /*纯白色的图片做背景, 歌词白色看不到了, 在背景前加入一个黑色半透明蒙层解决 */
      content: " ";
      background: rgba(0, 0, 0, 0.5);
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom:0;
    }
    .song-wrapper {
      position: fixed;
      width: 247px;
      height: 247px;
      left: 50%;
      top: 50px;
      transform: translateX(-50%);
      z-index: 10001;
    }
    .song-turn {
      width: 100%;
      height: 100%;
      background: url("./img/bg.png") no-repeat;
      background-size: 100%;
    }
    .start-box {
      position: absolute;
      width: 156px;
      height: 156px;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .song-start {
      width: 56px;
      height: 56px;
      background: url("./img/start.png");
      background-size: 100%;
    }
    .needle {
      position: absolute;
      transform-origin: left top;
      background: url("./img/needle-ab.png") no-repeat;
      background-size: contain;
      width: 73px;
      height: 118px;
      top: -40px;
      left: 112px;
      transition: all 0.6s;
    }
    .song-img {
      width: 154px;
      height: 154px;
      position: absolute;
      left: 50%;
      top: 50%;
      overflow: hidden;
      border-radius: 50%;
      transform: translate(-50%, -50%);
    }
    .m-song-h2 {
      margin-top: 20px;
      text-align: center;
      font-size: 18px;
      color: #fefefe;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .lrcContent {
      margin-top: 50px;
    }
    .lrc {
      font-size: 14px;
      color: #fff;
      text-align: center;
    }
    .left-incon {
      position: absolute;
      top: 10px;
      left: 10px;
      font-size: 24px;
      z-index: 10001;
      color: #fff;
    }
    .ani {
      animation: turn 5s linear infinite;
    }
    @keyframes turn {
      0% {
        -webkit-transform: rotate(0deg);
      }
      100% {
        -webkit-transform: rotate(360deg);
      }
    }
    style>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283

    api/index.js

    // axios发送ajax请求网络请求
    import axios from "axios";
    
    // axios.create()创建一个axios对象
    const request = axios.create({
        //基础路径,发请求的时候,路径当中会出现api,不用你手写
    	baseURL:'http://localhost:3000',
    	//请求时间超过5秒
    	timeout:5000
    });
    
    //获取音乐播放地址
    export const getSongByIdAPI = (params)=>request({url:"/song/url/v1",params});
    
    //获取歌词
    export const getLyricByIdAPI = (params)=>request({url:'/lyric',params});
    
    //获取歌曲详情
    export const getMusicByIdAPI = (params)=>request({url:'/song/detail',params})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    以上是实现网易云音乐播放页面并同步一次显示一行歌词代码,喜欢点点赞哦~~~

  • 相关阅读:
    Nacos服务发现与注册中心之服务消费(发现)者(客户端源码)
    【ArcGIS Pro二次开发】(75):ArcGIS Pro SDK二次开发中的常见问题及解决方法
    图解LeetCode——1752. 检查数组是否经排序和轮转得到(难度:简单)
    C++(17):模板嵌套类的.template及::template
    JSP基础知识
    JavaScript DOM API中append和appendChild的不同点
    js ?. 可选链
    详解设计模式:适配器模式
    UVM中config_db机制的使用方法
    闭包的常见问题
  • 原文地址:https://blog.csdn.net/Vest_er/article/details/127327285