美文网首页Web前端之路
Vue实现歌词滚动效果(lyric-parser)

Vue实现歌词滚动效果(lyric-parser)

作者: 学习前端ing | 来源:发表于2021-01-25 17:37 被阅读0次

Vue实现歌词滚动效果

本例运用了lyric-parser解析歌词插件

npm install lyric-parser -s

用法

 let lyric = new Lyric(lyricStr, handler)

 function hanlder({lineNum, txt}){
   // this hanlder called when lineNum change
 }

API

//播放歌词
play()

//暂停歌词
stop()

//歌词跳转
seek(startTime)

//切换播放/暂停状态
toggelePlay()

使用插件前

image.png

使用插件后

image.png

具体实现步骤

1、获取歌词,并new Lyric对象。

this.currentLyric = new Lyric(lyric, this.lyricHandle)

2、编写歌词回调函数,封装好滚动函数,此处用了better-scroll的scrollToElement。

// 歌词回调
lyricHandle({ lineNum, txt }) {
    console.log(lineNum)
    if (!this.$refs.lyricLine) {
        return
    }
    this.currentLyricNum = lineNum
    if(lineNum > 10) {
        let lineEl = this.$refs.lyricLine[lineNum - 10]
        if (this.$refs.lyricList) {
            this.$nextTick(() => {
                this.$refs.lyricList.scrollToElement(lineEl, 1000)
            })
        }
    } else {
        if (this.$refs.lyricList) {
            this.$nextTick(() => {
                this.$refs.lyricList.scrollTo(0, 0, 1000)
            })
        }
    }
    this.playingLyric = txt;
   },

3、根据时间的变化来触发seek()函数,每次调用seek()就会自动调用2中的函数

        // 进度条拖动改变播放进度
        onPercentBarChange(percent) {
            const currentTime = this.currentSong.duration * percent
            this.currentTime = this.$refs.audio.currentTime = currentTime
            if (this.currentLyric) {
                this.currentLyric.seek(currentTime * 1000)
            }
            if (!this.playing) {
                this.togglePlaying()
            }
        },

获取歌曲播放时时间可用audio的currentTime。

以上为本人对项目中遇到问题的一些见解,如有错误请指出,感谢您的观看。

相关文章

网友评论

    本文标题:Vue实现歌词滚动效果(lyric-parser)

    本文链接:https://www.haomeiwen.com/subject/lacizktx.html