当前位置:首页 > JavaScript

js如何实现歌词

2026-02-02 16:45:05JavaScript

实现歌词滚动的基本思路

歌词滚动功能通常需要同步音频播放时间与歌词显示。核心是将歌词文本按时间轴解析为数组,监听音频播放进度并匹配对应歌词行。

歌词数据格式处理

常见歌词格式为LRC,每行包含时间标签和文本。解析示例:

const lrcText = `[00:01.00]这是第一行歌词
[00:03.50]这是第二行歌词`;

function parseLRC(text) {
  const lines = text.split('\n');
  return lines.map(line => {
    const timeMatch = line.match(/\[(\d{2}):(\d{2})\.(\d{2})\]/);
    if (!timeMatch) return null;
    const min = parseInt(timeMatch[1]);
    const sec = parseInt(timeMatch[2]);
    const ms = parseInt(timeMatch[3]);
    const time = min * 60 + sec + ms / 100;
    const text = line.replace(timeMatch[0], '').trim();
    return { time, text };
  }).filter(Boolean);
}

歌词同步实现

监听音频时间更新并匹配当前歌词:

const audio = document.querySelector('audio');
const lyrics = parseLRC(lrcText);
let currentLine = 0;

audio.addEventListener('timeupdate', () => {
  const currentTime = audio.currentTime;
  while (
    currentLine < lyrics.length - 1 && 
    currentTime >= lyrics[currentLine + 1].time
  ) {
    currentLine++;
  }
  highlightLyric(currentLine);
});

界面渲染与高亮

动态更新DOM显示当前歌词:

function renderLyrics(container) {
  lyrics.forEach((line, index) => {
    const div = document.createElement('div');
    div.className = 'lyric-line';
    div.dataset.index = index;
    div.textContent = line.text;
    container.appendChild(div);
  });
}

function highlightLyric(index) {
  document.querySelectorAll('.lyric-line').forEach(el => {
    el.classList.remove('active');
  });
  const activeLine = document.querySelector(`[data-index="${index}"]`);
  if (activeLine) activeLine.classList.add('active');
}

平滑滚动优化

添加CSS实现平滑滚动效果:

.lyrics-container {
  height: 300px;
  overflow-y: auto;
  scroll-behavior: smooth;
}

.lyric-line {
  padding: 8px;
  transition: all 0.3s;
}

.lyric-line.active {
  color: #ff0000;
  font-size: 1.2em;
}

完整实现示例

结合所有功能的完整示例:

class LyricsPlayer {
  constructor(container, audioElement) {
    this.container = container;
    this.audio = audioElement;
    this.lines = [];
    this.currentLine = 0;
  }

  loadLRC(text) {
    this.lines = parseLRC(text);
    this.render();
  }

  render() {
    this.container.innerHTML = '';
    this.lines.forEach((line, index) => {
      const div = document.createElement('div');
      div.className = 'lyric-line';
      div.dataset.index = index;
      div.textContent = line.text;
      this.container.appendChild(div);
    });

    this.audio.addEventListener('timeupdate', this.update.bind(this));
  }

  update() {
    const currentTime = this.audio.currentTime;
    while (
      this.currentLine < this.lines.length - 1 && 
      currentTime >= this.lines[this.currentLine + 1].time
    ) {
      this.currentLine++;
    }
    this.highlight();
  }

  highlight() {
    const activeElement = this.container.querySelector('.active');
    if (activeElement) activeElement.classList.remove('active');

    const currentElement = this.container.querySelector(
      `[data-index="${this.currentLine}"]`
    );
    if (currentElement) {
      currentElement.classList.add('active');
      currentElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  }
}

js如何实现歌词

分享给朋友:

相关文章

vue如何实现记住我

vue如何实现记住我

实现“记住我”功能的步骤 在Vue中实现“记住我”功能通常涉及前端保存用户登录状态(如token)到本地存储,并在下次访问时自动恢复登录状态。以下是具体实现方法: 使用localStorage或…

vue如何实现曲线图

vue如何实现曲线图

使用 ECharts 实现曲线图 在 Vue 项目中安装 ECharts 依赖: npm install echarts --save 引入 ECharts 并创建基础图表组件: <te…

h5如何实现vr效果

h5如何实现vr效果

使用WebXR API实现VR效果 WebXR是浏览器中实现VR/AR的核心API,支持设备姿态追踪、渲染交互等功能。需在支持WebXR的设备(如Oculus、HTC Vive)或浏览器模拟环境中运行…

php如何实现直播

php如何实现直播

实现直播功能的方法 PHP可以通过结合其他技术和工具来实现直播功能。以下是几种常见的方法: 使用流媒体服务器 配置流媒体服务器如Nginx-RTMP、Red5或Wowza。这些服务器支持RTM…

vue如何实现重新实现主题

vue如何实现重新实现主题

Vue 主题切换的实现方法 使用 CSS 变量动态切换主题 定义主题相关的 CSS 变量,通过修改这些变量实现主题切换。在根元素(如 :root)中定义默认主题的变量,在特定类名下定义其他主题的变量。…

vue如何实现原理

vue如何实现原理

Vue 实现原理的核心机制 Vue.js 的核心实现原理基于响应式系统、虚拟 DOM 和组件化设计。以下是关键机制的详细解析: 响应式系统 Vue 通过 Object.defineProperty…