Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Lấy thời gian hiện tại của HTML Audio Player bằng JavaScript


HTMLAudioElement.currentTime trả về vị trí phát hiện tại (giây). Dùng Math.floor(currentTime / 60) cho phút, currentTime % 60 cho giây.

Ví dụ

Phát audio, nhấn nút xem timestamp:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Audio timestamp</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: green; }
  </style>
</head>
<body>
  <h1>Hiển thị timestamp của HTML Audio Player</h1>
  <audio class="audio" src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" controls></audio>
  <div class="result"></div>
  <button class="Btn">XEM THỜI GIAN</button>
  <h3>Phát nhạc, rồi nhấn nút để xem thời gian hiện tại</h3>
  <script>
    const resEle = document.querySelector('.result');
    const btn = document.querySelector('.Btn');
    const audio = document.querySelector('.audio');
    btn.addEventListener('click', () => {
      const ct = audio.currentTime;
      const mins = Math.floor(ct / 60);
      const secs = Math.floor(ct % 60);
      resEle.textContent = `${mins}:${secs.toString().padStart(2, '0')}`;
    });
  </script>
</body>
</html>

Kết quả

Định dạng MM:SS (ví dụ: 1:23).

Lưu ý: File audio phải accessible (CORS). Ví dụ dùng file sample công khai.