React歌词滚动效果(跟随音乐播放时间滚动)

首先给audio绑定更新时间事件

	const updateTime = e => {
		console.log(e.target.currentTime)
		setCurrentTime(e.target.currentTime);
	};


	<audio
				src={currentSong.url}
				ref={audio}
				onCanPlay={ready}
				onEnded={end}
				onTimeUpdate={updateTime}
			></audio>

当歌曲播放时间改变的时候会触发updateTime事件,如下所示

歌词json格式

[
    {
        "time": 2,
        "content": "采样曲:願い~あの頃のキミへ~",
        "contents": [
            "采样曲:願い~あの頃のキミへ~"
        ]
    },
    {
        "time": 12,
        "content": "中文填词:一只然",
        "contents": [
            "中文填词:一只然"
        ]
    },
    {
        "time": 15,
        "content": "OP(原属词曲版权公司):テレビ東京ミュージック 东京电视台音乐",
        "contents": [
            "OP(原属词曲版权公司):テレビ東京ミュージック 东京电视台音乐"
        ]
    },
    {
        "time": 19,
        "content": "本作品经过原词曲作者以及版权公司授权",
        "contents": [
            "本作品经过原词曲作者以及版权公司授权"
        ]
    },
    ......
    ]

接下来就是根据当前的播放时间显示歌词高亮,给歌词绑定高亮放大样式

.highlight {
color: $theme-color;
font-weight: $font-weight-bold;
font-size: 16px !important;
}
// 使用Redux的useSelector获取当前播放时间
const currentTime = useSelector(state => state.musicReducer.currentTime);

// 使用React的useMemo优化性能,只有当currentTime变化时,才会重新计算time的值
const time= useMemo(() => {
    return currentTime;
},[currentTime]);

// updateTime函数用于更新当前歌词的索引
const updateTime = e => {
    // 在所有歌词中找到第一个时间大于当前播放时间的歌词,其前一个歌词就是当前应该显示的歌词
    const currentLyricIndex = lyric.findIndex((lyricItem, index) => {
        // 判断是否是最后一项歌词,如果是,下一项歌词的时间设为无穷大
        const isLastItem = index === lyric.length - 1;
        const nextLyricTime = isLastItem ? Infinity : lyric[index + 1].time;
        // 如果当前播放时间在当前歌词和下一条歌词的时间之间,说明当前歌词应该被显示
        return time >= lyricItem.time && time < nextLyricTime;
    });
    // 更新当前歌词的索引
    setCurrentLyricIndex(currentLyricIndex);
};

// 使用React的useEffect在time变化时,调用updateTime函数,更新当前歌词的索引
useEffect(() => {
    updateTime()
}, [time]);

 当time发生变化时,调用updateTime函数来更新当前歌词的索引currentLyricIndex。确保在歌曲播放过程中,歌词随着时间的推移而更新。

最后,实现歌词滚动的效果

  1. 创建 scrollRef

    const scrollRef = useRef();

    使用 useRef 创建了一个 scrollRef,用于引用 Scroll 组件的实例。

  2. 使用 useEffect 进行歌词滚动:

        useEffect(() => {
            // 模拟异步加载歌词
            // 假设你要滚动到的歌词元素有一个特定的类名 ".lyric-item.highlight"
            const selector = '.lyric-item.highlight';
            // 调用 Scroll 组件的 scrollToElement 方法
            if (scrollRef.current) {
                scrollRef.current.scrollToElement(selector, 500); // 第二个参数是滚动时间,可以根据需要调整
            }
        }, [currentLyricIndex]);

    currentLyricIndex 发生变化时,useEffect 会被触发。在该效果中,它模拟异步加载歌词,然后通过 scrollRef.current.scrollToElement 方法滚动到指定的歌词元素,滚动时间为500毫秒。这样,每次歌词发生变化时都会滚动到当前高亮的歌词位置。

  3. Scroll 组件的 scrollToElement 方法实现:

            scrollToElement(selector, time = 0) {
                if (bScroll) {
                    const targetElement = document.querySelector(selector);
                    if (targetElement) {
                        const containerHeight = scrollContainerRef.current.clientHeight;
                        const targetHeight = targetElement.clientHeight;
                        const offsetTop = (containerHeight - targetHeight) / 2;
                        bScroll.scrollToElement(targetElement, time, 0, -offsetTop);
                    }
                }
            }

    这是 Scroll 组件内部的 scrollToElement 方法的实现。首先,通过 document.querySelector(selector) 获取到目标元素(具有指定类名的高亮歌词元素)。然后,计算目标元素相对于滚动容器的偏移,最后使用 bScroll.scrollToElement 将目标元素滚动到可视区域,传入的参数包括时间、水平和垂直的偏移。

相关推荐

  1. [React] 手动实现CountTo 数字滚动效果

    2024-03-15 18:00:07       11 阅读
  2. iOS 实现悬浮跟手滚动效果

    2024-03-15 18:00:07       22 阅读
  3. 纯css实现文字左右循环滚动播放效果

    2024-03-15 18:00:07       28 阅读
  4. react 屏幕信息滚动

    2024-03-15 18:00:07       11 阅读
  5. react 字轮播滚动

    2024-03-15 18:00:07       34 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-15 18:00:07       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-15 18:00:07       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-15 18:00:07       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-15 18:00:07       20 阅读

热门阅读

  1. c语言中的宏指的是什么

    2024-03-15 18:00:07       22 阅读
  2. ubuntu docker-compose 编排容器并且设置自启动

    2024-03-15 18:00:07       21 阅读
  3. 安卓实现沉浸式安卓状态栏实现

    2024-03-15 18:00:07       17 阅读
  4. 实景剧本杀小程序开发搭建

    2024-03-15 18:00:07       20 阅读
  5. Spring Boot写一个简单的PDF到Word的转换程序

    2024-03-15 18:00:07       19 阅读
  6. LinearLayout和RelativeLayout对比

    2024-03-15 18:00:07       22 阅读
  7. 利益相关者理论(stakeholder theory)

    2024-03-15 18:00:07       17 阅读
  8. 简单聊一下 Python asyncio

    2024-03-15 18:00:07       20 阅读
  9. 2085. 统计出现过一次的公共字符串

    2024-03-15 18:00:07       19 阅读
  10. MySQL--索引常见面试题详解

    2024-03-15 18:00:07       22 阅读
  11. Python中,如何检查一个变量是否存在?

    2024-03-15 18:00:07       19 阅读