set interval 이용해서 구현해 보았습니다. 참고 바랍니다.
<!DOCTYPE html>
<html>
<body>
<div id="player" data-uri="HuvLtCmNmVQ"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
videoId: document.getElementById('player').getAttribute('data-uri'),
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
console.log(player.getCurrentTime());
}
function onIntervalReached(){
if(player.getCurrentTime === undefined || player.getCurrentTime === ){
return;
}
console.log(player.getCurrentTime());
}
setInterval(onIntervalReached, 100);
</script>
</body>
</html>
|
cs |
이벤트 리스너처럼 사용할 수 있는 방법으로도 만들어 보았으니 취향에 맞는 거 사용하세요
<!DOCTYPE html>
<html>
<body>
<div id="player" data-uri="HuvLtCmNmVQ"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
videoId: document.getElementById('player').getAttribute('data-uri'),
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
console.log(player.getCurrentTime());
}
function createPlayTimeChecker(callBackFunction){
var previousPlayTime = 0;
return function(){
if(player.getCurrentTime === undefined || player.getCurrentTime === ){
return;
}
var currentPlayTime = player.getCurrentTime();
if(previousPlayTime !== currentPlayTime){
callBackFunction({
previousPlayTime: previousPlayTime,
currentPlayTime: currentPlayTime
});
previousPlayTime = currentPlayTime;
}
}
}
function onPlayTimeChanged(event){
console.log(event.currentPlayTime);
}
setInterval(createPlayTimeChecker(onPlayTimeChanged), 100);
</script>
</body>
</html>
|
cs |
두 번재 방식은 플레이 타임이 바뀔 때에만 콜백 함수를 호출하게끔 구성하였습니다. createPlayTimeCheck의 첫 번째 함수 파라미터로 콜백 함수를 주면 됩니다.