Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

เหตุการณ์ ondurationchange: รันสคริปตเมื่อระยะเวลาสื่อเปลี่ยนแปลง

เหตุการณ์ ondurationchange จะถูกกระตุ้นเมื่อระยะเวลาทั้งหมด (Duration) ของสื่อ (วิดีโอ/เสียง) เปลี่ยนแปลง เกิดขึ้นเมื่อ:

  • Metadata โหลดเสร็จ (Duration ทราบครั้งแรก) - Common
  • Stream แบบ Live/Adaptive: Duration อัปเดตระหว่างเล่น
  • เปลี่ยน Source (src) ใหม่

ตัวอย่างการใช้งาน

<!DOCTYPE HTML>
<html>
<body>
    <video width="300" height="200" controls ondurationchange="display(this)">
        <source src="/html5/foo.ogg" type="video/ogg" />
        <source src="/html5/foo.mp4" type="video/mp4" />
        เบราว์เซอร์ของคุณไม่รองรับองค์ประกอบ video
    </video>
    <script>
        function display(videoEl) {
            // duration = NaN หากยังไม่ทราบ
            const dur = videoEl.duration;
            if (isFinite(dur)) {
                console.log('Video Duration:', dur, 'seconds');
                document.getElementById('duration').textContent = formatTime(dur);
            } else {
                console.log('Duration: Unknown (NaN)');
            }
        }
        
        function formatTime(seconds) {
            const h = Math.floor(seconds / 3600);
            const m = Math.floor((seconds % 3600) / 60);
            const s = Math.floor(seconds % 60);
            return (h ? h + ':' : '') + m.toString().padStart(2, '0') + ':' + s.toString().padStart(2, '0');
        }
    </script>
    <p>ระยะเวลา: <span id="duration">โหลด中...</span></p>
</body>
</html>

Media Events ลำดับโหลด (Load Sequence)

  1. loadstart - เริ่มโหลด
  2. durationchange - Duration ทราบค่า (NaN → Number) ⬅️ ที่นี่
  3. loadedmetadata - Metadata พร้อม (Dimensions, Duration)
  4. loadeddata - Frame แรกพร้อม
  5. canplay - เล่นได้ (อาจ Buffering)
  6. canplaythrough - เล่นจบได้โดยไม่ Buffer

การประยุกต์ใช้

  • แสดงระยะเวลาวิดีโอใน UI (Player Controls)
  • Validate วิดีโอ (Reject หากสั้น/ยาวเกินไป)
  • คำนวณ Progress Bar Scale
  • Live Stream: อัปเดต Duration เมื่อ Segment ใหม่เพิ่ม

ตัวอย่าง: Custom Duration Display

const video = document.querySelector('video');
const durationEl = document.getElementById('duration');

video.addEventListener('durationchange', () => {
    if (isFinite(video.duration)) {
        durationEl.textContent = formatTime(video.duration);
        durationEl.style.opacity = '1';
    } else {
        durationEl.textContent = 'Live / Unknown';
        durationEl.style.opacity = '0.7';
    }
});

video.addEventListener('timeupdate', () => {
    const percent = (video.currentTime / video.duration) * 100;
    document.getElementById('progress').style.width = percent + '%';
});