HTML5 Video/Audio API cung cấp thuộc tính playbackRate để điều khiển tốc độ phát.
Thuộc tính chính
| Thuộc tính | Mô tả |
|---|---|
playbackRate | Tốc độ phát hiện tại. 1.0 = bình thường, 2.0 = gấp 2, 0.5 = chậm rãi, -1 = ngược. |
defaultPlaybackRate | Tốc độ phát mặc định khi load/video reset. |
Ví dụ: Điều khiển tốc độ phát
<video id="myVideo" width="400" controls>
<source src="video.mp4" type="video/mp4">
</video>
<div style="margin-top:10px">
<label>Tốc độ: <span id="speedDisplay">1.0</span>x</label>
<input type="range" id="speedControl" min="0.25" max="3" step="0.25" value="1">
</div>
<script>
var video = document.getElementById('myVideo');
var speedControl = document.getElementById('speedControl');
var speedDisplay = document.getElementById('speedDisplay');
speedControl.addEventListener('input', function() {
video.playbackRate = parseFloat(this.value);
speedDisplay.textContent = this.value;
});
// Hiển thị tốc độ thực tế (có thể khác do browser limit)
video.addEventListener('ratechange', function() {
speedDisplay.textContent = video.playbackRate.toFixed(2);
});
</script>
Thay đổi tốc độ qua JavaScript thuần
// Phát gấp 3 lần ngay từ đầu
document.querySelector('video').defaultPlaybackRate = 3.0;
document.querySelector('video').play();
// Phát gấp 2 lần (tùy chỉnh lúc chạy)
document.querySelector('video').playbackRate = 2.0;
// Phát ngược (reverse)
document.querySelector('video').playbackRate = -1.0;
Giới hạn trình duyệt
| Trình duyệt | Min | Max | Ghi chú |
|---|---|---|---|
| Chrome | 0.0625 | 16 | Âm thanh bị tắt nếu < 0.5 hoặc > 4 (mặc định) |
| Firefox | 0.125 | 16 | Hỗ trợ âm thanh ở tốc độ cao hơn |
| Safari | 0.5 | 2 | Giới hạn chặt, âm thanh bảo toàn tốt |
| Edge | 0.0625 | 16 | Giống Chrome |
Giữ nguyên pitch âm thanh (Preserve Pitch)
Mặc định, thay đổi tốc độ làm thay đổi cao độ giọng (chipmunk effect). Để giữ nguyên pitch:
// Chỉ hỗ trợ một số trình duyệt (Firefox, Chrome mới) video.preservesPitch = true; // Non-standard // Hoặc chuẩn hơn: video.mozPreservesPitch = true; // Firefox // WebKit: chưa hỗ trợ chuẩn, dùng Web Audio API
Web Audio API - Giữ pitch chuẩn (Advanced)
var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var source = audioCtx.createMediaElementSource(video); var pitchShifter = audioCtx.createPitchShifter ? audioCtx.createPitchShifter() : null; // Hoặc dùng thư viện: soundtouch.js, timbre.js