当前位置:首页 > 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;
}

完整实现示例

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

js如何实现歌词

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' });
    }
  }
}

分享给朋友:

相关文章

vue如何实现滚动

vue如何实现滚动

Vue 实现滚动的方法 使用原生 JavaScript 方法 在 Vue 中可以通过 window.scrollTo 或 Element.scrollIntoView 实现滚动。例如,滚动到页面顶部:…

vue如何实现原理

vue如何实现原理

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

java如何实现多态

java如何实现多态

多态的概念 多态是面向对象编程的三大特性之一(封装、继承、多态),指同一操作作用于不同对象时,可以产生不同的行为。Java中主要通过方法重写(Override)和接口/抽象类实现多态。 实现多态的三…

前段vue如何实现

前段vue如何实现

Vue 前端实现方法 Vue 是一款流行的前端框架,用于构建用户界面。以下是一些常见的 Vue 实现方法: 组件化开发 Vue 的核心思想是组件化开发。每个组件可以独立封装逻辑、模板和样式,便于复用…

vue如何实现404

vue如何实现404

实现 Vue 404 页面的方法 在 Vue 中实现 404 页面通常需要结合路由配置和动态路由匹配。以下是几种常见方法: 使用通配符路由匹配 在 Vue Router 配置中,可以通过 * 通配符…

vue如何实现图

vue如何实现图

Vue 实现图表的方法 Vue 中实现图表可以通过多种方式,常见的有使用第三方库或自定义实现。以下是几种常见的方法: 使用 ECharts ECharts 是一个功能强大的图表库,支持多种图表类型。…