Điều khiển video Youtube bằng JS
Bài đăng này đã không được cập nhật trong 7 năm
1. Introduction
Youtube là 1 mạng xã hội chia sẻ video rất nổi tiếng. Thỉnh thoảng bạn muốn nhúng một video vào trong web của bạn, sẽ thật tuyệt nếu bạn có thể điều khiển được sự hoạt động của video. Youtube Javascript Player API chính là thứ bạn cần.
IFrame player API cho phép bạn nhúng một trình chạy video Youtube vào trong website của bạn và điều khiển nó thông qua Javascript. Bạn có thể tạo playlist, play/pause hoặc stop videos hay tăng giảm âm lượng. Bạn cũng có thể thêm event listeners, chúng sẽ thực thi theo các player events như là thay đổi trạng thái hoặc thay đổi chất lượng video
Bài viết này sẽ giải thích làm thế nào để sử dụng IFrame API. Nó xác định các loại sự kiện khác nhau mà API có thể gửi và giải thích cách viết event listeners để phản hổi lại những event kia. Nó cũng khác hoàn toàn so với những Javascript function
2. Requirements
Đầu tiên browser của bạn phải hỗ trợ phương thức postMesssage của HTML5. Phần lớn browsers hiện nay đều support cái này, chỉ trừ IE 7
Tiếp theo là trong JS của bạn phải có hàm onYouTubeIframeAPIReady. Đây là hàm mà API sẽ gọi khi page đã download phần Javascript cho API
3. Let's Practice
3.1: Initialize player
Bước đầu tiên là phải có thẻ HTML để chứa video & load JS của API
<!-- The <iframe> (and video player) will replace this <div> tag. -->
<div id="video-container"></div>
<script src="https://www.youtube.com/iframe_api"></script>
Nhưng đã nói ở phần 1. Bạn sẽ phải khai báo 1 function GLOBAL onYouTubeIframeAPIReady() trong phần js của bạn
<div>chỉ định rõ vị trí trên trang, chỗ màIFrame APIsẽ thay thế video player vào đó. Hàm khởi tạo choplayer objectđược mô tả trong phần dưới đây
let player, time_update_interval;
function onYouTubeIframeAPIReady() {
player = new YT.Player('video-container', {
width: 600,
height: 400,
videoId: 'v63Z_NCdYqQ',
playerVars: {
playlist: 'z1Ev1Z0cCG4,FG0fTKAqZ5g',
// autoplay: 1,
// controls: 0
},
events: {
onReady: initialize
}
});
}
function initialize(){
// Update the controls on load
updateTimerDisplay();
updateProgressBar();
// Clear any old interval.
clearInterval(time_update_interval);
// Start interval to update elapsed time display and
// the elapsed part of the progress bar every second.
time_update_interval = setInterval(function () {
updateTimerDisplay();
updateProgressBar();
}, 1000)
}
Tham số đầu tiên của hàm YT.Player là id của thẻ sẽ chứa video. IFrame API sẽ thay thế thẻ này bằng thẻ <iframe> chứa video
Tham số thứ 2 là những option của player
onYouTubeIframeAPIReadyhàm này sẽ được thực thi ngay sau khi codeplayer APIđược tải xuống. Phần code này định nghĩa 1 biến globalplayer, nó ám chỉ đến video player mà bạn đang nhúng vào trangwidth/heightlà kích thước của iframe chứa videovideoIdlà video mà bạn muốn play lúc ban đầu. Id này chính là param trên url của mỗi video. VD ta có 1 đường dẫn video:https://www.youtube.com/watch?v=CPkGTSW34_Ithì videoId chính làCPkGTSW34_IplayerVarslà những thuộc tính của player. Bạn có thể tham khảo thêm tại đâyeventslà chứa những function cho mỗi sự kiện. Ở đây mình khai báo 1 hàminitializevới event làonReadyđể hiển thị phần timer & progressBarinitializehàm này có nhiệm vụ hiển thị thời lượng video, time current của video đang play cũng như hiển thị thanh progressbar. Để làm được việc này ta cần thêm 1 chút code nữa
----------------- HTML ----------------
<li>
<h2>Duration</h2>
<p><span id="current-time">0:00</span> / <span id="duration">0:00</span></p>
</li>
<li>
<h2>Progress Bar</h2>
<input type="range" id="progress-bar" value="0">
</li>
----------------- JS -------------------
// This function is called by initialize()
function updateTimerDisplay() {
// Update current time text display.
$('#current-time').text(formatTime(player.getCurrentTime()));
$('#duration').text(formatTime(player.getDuration()));
}
function formatTime(time) {
return moment(0).add(moment.duration({'seconds': time})).format('mm:ss');
}
// This function is called by initialize()
function updateProgressBar() {
// Update the value of our progress bar accordingly.
$('#progress-bar').val((player.getCurrentTime() / player.getDuration()) * 100);
}
3.2: Play/pause
Giờ mình đã có biến player là 1 object của Player rồi. Nên muốn thao tác gì đến video thì chỉ cần tóm thằng này mà dùng
Ta có 2 button
<li>
<h2>Play</h2>
<i id="play" class="material-icons">play_arrow</i>
</li>
<li>
<h2>Pause</h2>
<i id="pause" class="material-icons">pause</i>
</li>
và để play/pause video thì chỉ cần gọi
$('#play').on('click', function () {
player.playVideo();
});
$('#pause').on('click', function () {
player.pauseVideo();
});
3.3: Control Volume
Ta có 1 button để Mute/Unmute & 1 input để nhập âm lượng
<li>
<h2>Mute / Unmute</h2>
<i id="mute-toggle" class="material-icons">volume_up</i>
</li>
<li>
<h2>Set volume</h2>
<input id="volume-input" type="number" max="100" min="0">
</li>
Để thao tác
$('#mute-toggle').on('click', function () {
var mute_toggle = $(this);
if (player.isMuted()) {
player.unMute();
mute_toggle.text('volume_up');
}
else {
player.mute();
mute_toggle.text('volume_off');
}
});
$('#volume-input').on('change', function () {
player.setVolume($(this).val());
});
Như vậy là mình đã giới thiệu cho bạn cách điều khiển 1 video của Youtube thông qua IFrame Player API
Bạn có thể tham khảo thêm những function khác ở đây
All rights reserved