HTML - Audio Player

Chào mừng các bạn đang học lập trình web! Hôm nay, chúng ta sẽ khám phá thế giới thú vị của các bộ phát音频 HTML. Cuối bài hướng dẫn này, bạn sẽ có khả năng tạo riêng bộ phát audio tùy chỉnh của mình và thậm chí thêm một số hiệu ứng thị giác tuyệt vời. Hãy cùng戴上 mũ lập trình và bắt đầu hành trình âm nhạc này!

HTML - Audio Player

HTML Local Audio Player với Trình Tạo Ảnh

Cơ bản về Audio HTML

Trước khi chúng ta nhảy vào tạo một bộ phát audio sang trọng, hãy bắt đầu từ những điều cơ bản. HTML5 đã giới thiệu thẻ <audio>, giúp việc thêm audio vào trang web của bạn trở nên siêu dễ dàng. Dưới đây là một ví dụ đơn giản:

<audio controls>
<source src="your-audio-file.mp3" type="audio/mpeg">
Trình duyệt của bạn không hỗ trợ thẻ audio.
</audio>

Trong đoạn mã này:

  • Thẻ <audio> tạo ra một bộ phát audio.
  • Thuộc tính controls thêm các nút phát, dừng và điều chỉnh âm lượng.
  • Thẻ <source> chỉ định tệp audio để phát.
  • Chúng ta bao gồm một thông báo dự phòng cho các trình duyệt không hỗ trợ thẻ <audio>.

Tạo một Bộ Phát Audio Tùy Chỉnh

Bây giờ, hãy tạo một bộ phát audio tùy chỉnh hơn. Chúng ta sẽ sử dụng HTML, CSS và JavaScript để xây dựng này:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Audio Player</title>
<style>
#custom-player {
width: 300px;
padding: 20px;
background-color: #f0f0f0;
border-radius: 10px;
}
#play-pause-btn {
width: 100px;
height: 30px;
}
#seek-bar {
width: 100%;
margin-top: 10px;
}
</style>
</head>
<body>
<div id="custom-player">
<audio id="audio-element" src="your-audio-file.mp3"></audio>
<button id="play-pause-btn">Phát</button>
<input type="range" id="seek-bar" value="0">
</div>

<script>
const audio = document.getElementById('audio-element');
const playPauseBtn = document.getElementById('play-pause-btn');
const seekBar = document.getElementById('seek-bar');

playPauseBtn.addEventListener('click', () => {
if (audio.paused) {
audio.play();
playPauseBtn.textContent = 'Dừng';
} else {
audio.pause();
playPauseBtn.textContent = 'Phát';
}
});

audio.addEventListener('timeupdate', () => {
const progress = (audio.currentTime / audio.duration) * 100;
seekBar.value = progress;
});

seekBar.addEventListener('input', () => {
const time = (seekBar.value / 100) * audio.duration;
audio.currentTime = time;
});
</script>
</body>
</html>

Giải thích đoạn mã này:

  1. Chúng ta tạo một contain <div> cho bộ phát audio tùy chỉnh của mình.
  2. Trong đó, chúng ta có một thẻ <audio> (không có controls), một nút phát/dừng và một thanh seek.
  3. Trong JavaScript:
  • Chúng ta chuyển đổi giữa phát và dừng khi nhấn nút.
  • Chúng ta cập nhật thanh seek khi audio phát.
  • Chúng ta cho phép seek bằng cách nhấp vào thanh seek.

Thêm Trình Tạo Ảnh

Bây giờ, hãy thêm một trình tạo ảnh đơn giản để làm cho bộ phát audio của chúng ta hấp dẫn hơn. Chúng ta sẽ sử dụng Web Audio API cho điều này:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audio Player với Trình Tạo Ảnh</title>
<style>
#custom-player {
width: 300px;
padding: 20px;
background-color: #f0f0f0;
border-radius: 10px;
}
#play-pause-btn {
width: 100px;
height: 30px;
}
#seek-bar {
width: 100%;
margin-top: 10px;
}
#visualizer {
width: 300px;
height: 150px;
background-color: #000;
margin-top: 10px;
}
</style>
</head>
<body>
<div id="custom-player">
<audio id="audio-element" src="your-audio-file.mp3"></audio>
<button id="play-pause-btn">Phát</button>
<input type="range" id="seek-bar" value="0">
<canvas id="visualizer"></canvas>
</div>

<script>
const audio = document.getElementById('audio-element');
const playPauseBtn = document.getElementById('play-pause-btn');
const seekBar = document.getElementById('seek-bar');
const canvas = document.getElementById('visualizer');
const ctx = canvas.getContext('2d');

// Thiết lập audio context
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioContext.createAnalyser();
const source = audioContext.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(audioContext.destination);

// Chức năng phát/dừng
playPauseBtn.addEventListener('click', () => {
if (audioContext.state === 'suspended') {
audioContext.resume();
}
if (audio.paused) {
audio.play();
playPauseBtn.textContent = 'Dừng';
} else {
audio.pause();
playPauseBtn.textContent = 'Phát';
}
});

// Chức năng thanh seek
audio.addEventListener('timeupdate', () => {
const progress = (audio.currentTime / audio.duration) * 100;
seekBar.value = progress;
});

seekBar.addEventListener('input', () => {
const time = (seekBar.value / 100) * audio.duration;
audio.currentTime = time;
});

// Trình tạo ảnh
function drawVisualizer() {
requestAnimationFrame(drawVisualizer);

const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
analyser.getByteFrequencyData(dataArray);

ctx.fillStyle = 'rgb(0, 0, 0)';
ctx.fillRect(0, 0, canvas.width, canvas.height);

const barWidth = (canvas.width / bufferLength) * 2.5;
let x = 0;

for (let i = 0; i < bufferLength; i++) {
const barHeight = dataArray[i] / 2;

ctx.fillStyle = `rgb(${barHeight + 100}, 50, 50)`;
ctx.fillRect(x, canvas.height - barHeight, barWidth, barHeight);

x += barWidth + 1;
}
}

drawVisualizer();
</script>
</body>
</html>

Trong phiên bản được cải tiến này:

  1. Chúng ta thêm một thẻ <canvas> cho trình tạo ảnh.
  2. Chúng ta thiết lập audio context và analyzer sử dụng Web Audio API.
  3. Hàm drawVisualizer tạo một biểu đồ thanh của tần số âm thanh.

Bộ Phát Audio với Danh Sách Bài Hát

Bây giờ, hãy tạo một bộ phát audio có thể xử lý nhiều bài hát:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audio Player với Danh Sách Bài Hát</title>
<style>
#playlist-player {
width: 300px;
padding: 20px;
background-color: #f0f0f0;
border-radius: 10px;
}
#play-pause-btn, #prev-btn, #next-btn {
width: 80px;
height: 30px;
margin: 5px;
}
#seek-bar {
width: 100%;
margin-top: 10px;
}
#playlist {
list-style-type: none;
padding: 0;
}
#playlist li {
cursor: pointer;
padding: 5px;
}
#playlist li:hover {
background-color: #ddd;
}
</style>
</head>
<body>
<div id="playlist-player">
<audio id="audio-element"></audio>
<button id="prev-btn">Trước</button>
<button id="play-pause-btn">Phát</button>
<button id="next-btn">Tiếp</button>
<input type="range" id="seek-bar" value="0">
<ul id="playlist">
<li data-src="song1.mp3">Bài Hát 1</li>
<li data-src="song2.mp3">Bài Hát 2</li>
<li data-src="song3.mp3">Bài Hát 3</li>
</ul>
</div>

<script>
const audio = document.getElementById('audio-element');
const playPauseBtn = document.getElementById('play-pause-btn');
const prevBtn = document.getElementById('prev-btn');
const nextBtn = document.getElementById('next-btn');
const seekBar = document.getElementById('seek-bar');
const playlist = document.getElementById('playlist');
let currentTrack = 0;

function loadTrack(index) {
const tracks = playlist.getElementsByTagName('li');
if (index >= 0 && index < tracks.length) {
currentTrack = index;
audio.src = tracks[currentTrack].getAttribute('data-src');
audio.load();
playPauseBtn.textContent = 'Phát';
}
}

function playPause() {
if (audio.paused) {
audio.play();
playPauseBtn.textContent = 'Dừng';
} else {
audio.pause();
playPauseBtn.textContent = 'Phát';
}
}

playPauseBtn.addEventListener('click', playPause);

prevBtn.addEventListener('click', () => {
loadTrack(currentTrack - 1);
});

nextBtn.addEventListener('click', () => {
loadTrack(currentTrack + 1);
});

audio.addEventListener('timeupdate', () => {
const progress = (audio.currentTime / audio.duration) * 100;
seekBar.value = progress;
});

seekBar.addEventListener('input', () => {
const time = (seekBar.value / 100) * audio.duration;
audio.currentTime = time;
});

playlist.addEventListener('click', (e) => {
if (e.target.tagName === 'LI') {
const tracks = playlist.getElementsByTagName('li');
loadTrack([...tracks].indexOf(e.target));
playPause();
}
});

loadTrack(0);
</script>
</body>
</html>

Trong phiên bản danh sách bài hát:

  1. Chúng ta tạo một danh sách bài hát sử dụng một danh sách không có样式.
  2. Chúng ta thêm các nút trước và tiếp để điều hướng.
  3. JavaScript xử lý việc tải bài hát, phát/dừng và chuyển đổi giữa các bài hát.

Phương Thức của Bộ Phát Audio

Dưới đây là bảng các phương thức bộ phát audio phổ biến và mô tả của chúng:

Phương Thức Mô Tả
play() Bắt đầu phát audio
pause() Dừng phát audio
load() Tải lại phần tử audio
currentTime Lấy hoặc đặt vị trí phát hiện tại (giây)
duration Lấy tổng thời gian của audio (giây)
volume Lấy hoặc đặt âm lượng (0.0 đến 1.0)
muted Lấy hoặc đặt xem audio có bị tắt tiếng hay không
playbackRate Lấy hoặc đặt tốc độ phát

Và thế là xong! Bạn đã học cách tạo các bộ phát audio HTML cơ bản và nâng cao, kèm theo trình tạo ảnh và danh sách bài hát. Hãy nhớ rằng, thực hành là cách tốt nhất để trở thành chuyên gia, vì vậy đừng ngần ngại thử nghiệm và tùy chỉnh các ví dụ này để phù hợp với nhu cầu của bạn. Chúc bạn may mắn và hy vọng trang web của bạn sẽ đầy âm nhạc đẹp đẽ!

Credits: Image by storyset