当前位置:首页 > JavaScript

js实现歌词

2026-02-01 23:09:38JavaScript

实现歌词滚动效果

使用HTML和JavaScript实现歌词滚动效果需要结合音频播放器的当前时间与歌词时间轴同步。以下是实现方法:

创建HTML结构包含音频播放器和歌词显示区域:

<audio id="audioPlayer" src="song.mp3"></audio>
<div id="lyricsContainer"></div>

准备歌词数据,通常采用LRC格式的时间标签:

js实现歌词

const lyrics = [
  { time: 0.5, text: "第一句歌词" },
  { time: 3.2, text: "第二句歌词" },
  { time: 5.8, text: "第三句歌词" }
  // 更多歌词...
];

实现歌词同步逻辑:

const audio = document.getElementById('audioPlayer');
const container = document.getElementById('lyricsContainer');

audio.addEventListener('timeupdate', () => {
  const currentTime = audio.currentTime;
  let activeIndex = -1;

  lyrics.forEach((line, index) => {
    if (currentTime >= line.time && 
        (index === lyrics.length - 1 || currentTime < lyrics[index + 1].time)) {
      activeIndex = index;
    }
  });

  updateLyricsDisplay(activeIndex);
});

function updateLyricsDisplay(activeIndex) {
  container.innerHTML = '';
  lyrics.forEach((line, index) => {
    const p = document.createElement('p');
    p.textContent = line.text;
    p.className = index === activeIndex ? 'active' : '';
    container.appendChild(p);
  });

  if (activeIndex >= 0) {
    const activeLine = container.children[activeIndex];
    activeLine.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }
}

添加CSS样式增强视觉效果

为歌词添加基本样式和活动歌词高亮效果:

js实现歌词

#lyricsContainer {
  height: 300px;
  overflow-y: auto;
  text-align: center;
  font-size: 18px;
  line-height: 2;
}

#lyricsContainer p.active {
  color: #ff5500;
  font-weight: bold;
  font-size: 22px;
}

处理动态加载歌词

从LRC文件或API加载歌词数据:

async function loadLyrics(url) {
  const response = await fetch(url);
  const lrcText = await response.text();
  return parseLRC(lrcText);
}

function parseLRC(lrcText) {
  const lines = lrcText.split('\n');
  const result = [];

  lines.forEach(line => {
    const timeMatch = line.match(/^\[(\d+):(\d+\.\d+)\]/);
    if (timeMatch) {
      const minutes = parseFloat(timeMatch[1]);
      const seconds = parseFloat(timeMatch[2]);
      const time = minutes * 60 + seconds;
      const text = line.replace(timeMatch[0], '').trim();
      result.push({ time, text });
    }
  });

  return result.sort((a, b) => a.time - b.time);
}

实现歌词搜索功能

为长歌词添加搜索功能:

function searchLyrics(keyword) {
  const results = lyrics.filter(line => 
    line.text.toLowerCase().includes(keyword.toLowerCase())
  );

  if (results.length > 0) {
    const firstMatchIndex = lyrics.findIndex(line => line === results[0]);
    audio.currentTime = lyrics[firstMatchIndex].time - 0.5;
    updateLyricsDisplay(firstMatchIndex);
  }
}

添加播放控制按钮

扩展播放器控制功能:

document.getElementById('playBtn').addEventListener('click', () => {
  audio.play();
});

document.getElementById('pauseBtn').addEventListener('click', () => {
  audio.pause();
});

document.getElementById('seekBack').addEventListener('click', () => {
  audio.currentTime -= 5;
});

document.getElementById('seekForward').addEventListener('click', () => {
  audio.currentTime += 5;
});

标签: 歌词js
分享给朋友:

相关文章

js实现轮播

js实现轮播

实现基础轮播效果 使用HTML结构创建轮播容器和图片元素: <div class="carousel"> <div class="carousel-inner">…

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-contain…

js实现验证

js实现验证

验证表单输入 使用JavaScript验证表单输入是常见的需求。可以通过监听表单提交事件,检查输入字段是否符合要求。 document.getElementById('myForm').addEv…

jquery.js

jquery.js

jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互等操作。以下是关于 jQuery.js 的核心信息和使用方法: 获取 j…

js轮播图实现原理

js轮播图实现原理

轮播图的基本原理 轮播图通过动态切换显示的内容(图片、文本等)实现视觉上的滑动效果。核心原理是利用CSS和JavaScript控制元素的显示与隐藏,或通过变换位置实现滑动动画。 实现方法一:CSS…