유튜브 반응형 커스텀 플레이어 하나 : 코드 업뎃 > 그누보드5 팁자료실

그누보드5 팁자료실

유튜브 반응형 커스텀 플레이어 하나 : 코드 업뎃 정보

유튜브 반응형 커스텀 플레이어 하나 : 코드 업뎃

본문

 

[2] - [ 2023 년 01월 19일 코드 업데이트 ]

setInterval 과 getCurrentTime() 이 충돌하는 오류를 수정하였습니다.

 

[1] - [ 2023 년 01월 01일 코드 업데이트 ]

@스펀지둘님이 댓글에서 제기한 부분을 수정하였습니다.

 

---------------------

 

이번에 유튜브 동영상으로 강의용 게시판을 만들면서 커스텀한 플레이어 코드를 하나 공유합니다.

유튜브 자체 미디어바를 없애고 플레이어 부분을 좀 만졌습니다.

응용할 분은 알아서 사용하세요.

유튜브 아이디 대입 부분은 아이프레임에서 src 의 가장 마지막인 playlist=11자리문자열 입니다.

자동재생 무한반복으로 하나의 동영상을 걸었는데 자동재생은 상황에 따라 안 될 수도 있습니다.^^

 


<link href="https://fonts.googleapis.com/css2?family=Lato" rel="stylesheet">
<style>
#ytDiv { position:relative; padding-top:56.25%; overflow:hidden; background-color:#000000; }
#ytDiv iframe { display:block; position:absolute; top:0%; left:50%; transform:translate(-50%); width:100%; height:100%; border:none; }
#ytDiv div:nth-of-type(1) { display:none; position:absolute;top:0%; width:100%;height:100%; }
#ytDiv div:nth-of-type(2) { position:absolute; top:0%; width:100%; height:40%; background:linear-gradient(#000000 30%, transparent); }
#ytDiv div:nth-of-type(3) { position:absolute; top:60%; width:100%; height:40%; background:linear-gradient(transparent, #000000 70%); }
#playerDiv { width:100%; height:50px; padding:0px 25px 0px 25px; display:none; justify-content:space-between; align-items:center; gap:15px; box-sizing:border-box; background:linear-gradient(#cccccc, #000000); }
.yt-button { color:#fae100; font-size:16px; font-family:Lato; font-weight:bold; cursor:pointer; }
.yt-timer { color:#ffffff; font-size:16px; font-family:Lato; }
#ytBar { display:block; width:100%; height:12px; cursor:pointer; appearance:none; }
#ytBar::-webkit-progress-bar { background-color:#eeeeee; border-radius:6px; border:1px solid #cccccc; }
#ytBar::-webkit-progress-value { background-color:#fae100; border-radius:6px; }
</style>
<div id="ytDiv">
    <iframe src="//www.youtube.com/embed/?loop=1&vq=highres&enablejsapi=1&autoplay=1&playlist=fWNaR-rxAic" allow="autoplay"></iframe>
    <div></div><div></div><div></div>
</div>
<div id="playerDiv">
    <span class="yt-button" onclick="ytDiv.playVideo()">PLAY</span>
    <span class="yt-timer">00:00</span>
    <progress id="ytBar"></progress>
    <span class="yt-timer">00:00</span>
    <span class="yt-button" onclick="ytDiv.pauseVideo()">STOP</span>
</div>
<script src="https://www.youtube.com/iframe_api"></script>
<script>
function onYouTubeIframeAPIReady() {
    ytDiv = new YT.Player(ytDiv.querySelector("iframe"), { events: {"onStateChange":onPlayerStateChange} });
}
function onPlayerStateChange(event) {
    if (event.data === 1) {
        document.querySelector("#ytDiv div").style.display = "block";
        document.querySelectorAll("#ytDiv div")[1].style.display = document.querySelectorAll("#ytDiv div")[2].style.display = "none";
        document.querySelector("#ytDiv iframe").style.top = "-150%";
        document.querySelector("#ytDiv iframe").style.height = "400%";
        playerDiv.style.display = "flex";
        ytBar.max = Math.floor(ytDiv.getDuration());
        document.querySelectorAll(".yt-timer")[1].innerText = ("0" + Math.floor(ytDiv.getDuration() / 60)).slice(-2) + ":" + ("0" + Math.floor(ytDiv.getDuration() % 60)).slice(-2);
        setInterval(() => {
            ytBar.value = Math.floor(ytDiv.getCurrentTime());
            document.querySelectorAll(".yt-timer")[0].innerText = ("0" + Math.floor(ytDiv.getCurrentTime() / 60)).slice(-2) + ":" + ("0" + Math.floor(ytDiv.getCurrentTime() % 60)).slice(-2);
        }, 500);
    }
}
ytBar.onclick = (e) => {
    ytDiv.seekTo(e.offsetX * ytBar.max / ytBar.offsetWidth);
    ytDiv.playVideo();
}
</script>

 

https://wittazzurri.com/editor/html_editor.php 에서 확인해 보세요.

주의사항은 중간에 광고 등이 나타나 끊기는 동영상은 다른 코드를 좀 추가해야 합니다.

 

원본은 https://www.youtube.com/watch?v=fWNaR-rxAic 입니다.

추천
10

댓글 31개


세로를 늘이면 아래처럼 되죠. 광고는 없는 것이 아니라 하단부에 있습니다.
아래처럼 세로를 늘여서 동영상을 띄운 후에 css 로 상하단을 절단하여 중앙부분만 취하는 꼼수입니다.ㅋ


이렇게만 띄우면 유튜브 아이프레임에서 우클릭으로 컨트롤 할 수도 있어서 그것도 막아야 해요. 그래서 동일사이즈의 투명 진공 div 로 동영상을 덮어서 우클릭을 못하도록 방지해야 합니다.
하지만 첫 재생이 수동재생일 경우에는 동영상을 클릭해야만 재생이 되기 때문에 처음부터 진공 div 가 동영상을 덮어서는 안 됩니다.
따라서 셋인터벌로 진공 div 가 동영상의 현재시간이 0초보다 클 때에만 나타나도록 또 코드를 주어야지요.
이것저것 디테일이 꽤 들어간 코드입니다.ㅋ
개발이 메인 직업이 아니라서 마음에 여유가 있어 그렇습니다.
아 이건 해 보고 싶은 것이었다. 딱 내 취향이다라는 컨텐츠면서 시간문제로 닥달 안하는 고객만 받아요.
대신 의뢰받은 건 한 포인트도 놓치지 않고 정말 꼼꼼하게 체크하는 편이라 완성본을 넘기면 오류 문제로 연락오는 건 거의 없고 추가기능 때문에 오는 편이지요.
멋지네요.~ 광고 숨기는 꼼수도 감사합니다. 원리를 이해 했어요~
제가 이용하는 https://livemusic.co.kr
여기도 이런 방식일까요? 광고가 안나와요..신기하게~

하지만 미디어바와 타이틀이 떠억 보이잖아요
제겐 광고보다 더 보기 싫습니다.ㅋ

어떤 방식인지는 잘 모르겠습니다. 이미 제가  만들어논 코드가 있어서 그리 관심이 없다는게 맞는 말일 거에요.

새해 복많이 받으세요.
요즘 브라우저가 자동재생이 제대로 동작을 안해서 시작할때 사진? 이 기본으로 보여지는거 같은데요.
사진처럼 위는 비타주리님 코드인데 아래처럼 이미지가 확대안되고 제대로 보여질수는 없을까요?
새해복많이 받으세요^^
감사하네요. 다시 코드를 짜주시다니^^ 저는 근데 한참 검정화면으로 로딩되더니 아래 화면이 뜨네요. 배경이미지를 못찾는건가요?
다른 동영상으로 해 보세요. 동영상 올린 사람이 비공개 설정하면 유튜브 사이트에서만 보이고 다른 웹페이지에서는 안 보입니다.
테스트 페이지에서 코드넣고 결과보기 하면 잘 되는데 html로 만들어서 해보면 왜 안될까요? 제가 뭐를 잘못 넣었을까요?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="content-type" content="text/html; charset=euc-kr" />
<meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="imagetoolbar" content="no">

<title>test</title> 

<link href="https://fonts.googleapis.com/css2?family=Lato" rel="stylesheet">
<style>
#ytDiv { position:relative; padding-top:56.25%; overflow:hidden; background-color:#000000; }
#ytDiv iframe { display:block; position:absolute; top:0%; width:100%; height:100%; border:none; }
#ytDiv div:nth-of-type(1) { display:none; position:absolute;top:0%; width:100%;height:100%; }
#ytDiv div:nth-of-type(2) { position:absolute; top:0%; width:100%; height:40%; background:linear-gradient(#000000 30%, transparent); }
#ytDiv div:nth-of-type(3) { position:absolute; top:60%; width:100%; height:40%; background:linear-gradient(transparent, #000000 70%); }
#playerDiv { width:100%; height:50px; padding:0px 25px 0px 25px; display:none; justify-content:space-between; align-items:center; gap:15px; box-sizing:border-box; background:linear-gradient(#cccccc, #000000); }
.yt-button { color:#fae100; font-size:16px; font-family:Lato; font-weight:bold; cursor:pointer; }
.yt-timer { color:#ffffff; font-size:16px; font-family:Lato; }
#ytBar { display:block; width:100%; height:12px; cursor:pointer; appearance:none; }
#ytBar::-webkit-progress-bar { background-color:#eeeeee; border-radius:6px; border:1px solid #cccccc; }
#ytBar::-webkit-progress-value { background-color:#fae100; border-radius:6px; }
</style>

</head>
<body>
<div id="ytDiv">
    <iframe src="//www.youtube.com/embed/?loop=1&vq=highres&enablejsapi=1&autoplay=1&playlist=fWNaR-rxAic" allow="autoplay"></iframe>
    <div></div><div></div><div></div>
</div>
<div id="playerDiv">
    <span class="yt-button" onclick="ytDiv.playVideo()">PLAY</span>
    <span class="yt-timer">00:00</span>
    <progress id="ytBar"></progress>
    <span class="yt-timer">00:00</span>
    <span class="yt-button" onclick="ytDiv.pauseVideo()">STOP</span>
</div>
<script>
function onYouTubeIframeAPIReady() {
    ytDiv = new YT.Player(ytDiv.querySelector("iframe"));
    setInterval(() => {
        if (ytDiv.getCurrentTime() > 0) {
            document.querySelector("#ytDiv div").style.display = "block";
            document.querySelectorAll("#ytDiv div")[1].style.display = document.querySelectorAll("#ytDiv div")[2].style.display = "none";
            document.querySelector("#ytDiv iframe").style.top = "-150%";
            document.querySelector("#ytDiv iframe").style.height = "400%";
            playerDiv.style.display = "flex";
        }
        ytBar.value = Math.floor(ytDiv.getCurrentTime());
        ytBar.max = Math.floor(ytDiv.getDuration());
        document.querySelectorAll(".yt-timer")[0].innerText = ("0" + Math.floor(ytDiv.getCurrentTime() / 60)).slice(-2) + ":" + ("0" + Math.floor(ytDiv.getCurrentTime() % 60)).slice(-2);
        document.querySelectorAll(".yt-timer")[1].innerText = ("0" + Math.floor(ytDiv.getDuration() / 60)).slice(-2) + ":" + ("0" + Math.floor(ytDiv.getDuration() % 60)).slice(-2);
    }, 100);
}
ytBar.onclick = (e) => {
    ytDiv.seekTo(e.offsetX * ytBar.max / ytBar.offsetWidth);
    ytDiv.playVideo();
}
</script>
</body>
</html>

아니 왜 독타입을 삼국시대 독타입으로 선언하시나요? html5 로 선언하셔야죠.
이건 기본 중의 왕기본인데요.ㅜㅠ


<!DOCTYPE html>

<html>

<head>
<meta charset="UTF-8">
<title>[ Youtube Test ]</title>
</head>

<body>

<link href="https://fonts.googleapis.com/css2?family=Lato" rel="stylesheet">
<style>
#ytDiv { position:relative; padding-top:56.25%; overflow:hidden; background-color:#000000; }
#ytDiv iframe { display:block; position:absolute; top:0%; width:100%; height:100%; border:none; }
#ytDiv div:nth-of-type(1) { display:none; position:absolute;top:0%; width:100%;height:100%; }
#ytDiv div:nth-of-type(2) { position:absolute; top:0%; width:100%; height:40%; background:linear-gradient(#000000 30%, transparent); }
#ytDiv div:nth-of-type(3) { position:absolute; top:60%; width:100%; height:40%; background:linear-gradient(transparent, #000000 70%); }
#playerDiv { width:100%; height:50px; padding:0px 25px 0px 25px; display:none; justify-content:space-between; align-items:center; gap:15px; box-sizing:border-box; background:linear-gradient(#cccccc, #000000); }
.yt-button { color:#fae100; font-size:16px; font-family:Lato; font-weight:bold; cursor:pointer; }
.yt-timer { color:#ffffff; font-size:16px; font-family:Lato; }
#ytBar { display:block; width:100%; height:12px; cursor:pointer; appearance:none; }
#ytBar::-webkit-progress-bar { background-color:#eeeeee; border-radius:6px; border:1px solid #cccccc; }
#ytBar::-webkit-progress-value { background-color:#fae100; border-radius:6px; }
</style>

<div style="max-width:960px;margin:0 auto">
<div id="ytDiv">
    <iframe src="//www.youtube.com/embed/?loop=1&vq=highres&enablejsapi=1&autoplay=1&playlist=fWNaR-rxAic" allow="autoplay"></iframe>
    <div></div><div></div><div></div>
</div>
<div id="playerDiv">
    <span class="yt-button" onclick="ytDiv.playVideo()">PLAY</span>
    <span class="yt-timer">00:00</span>
    <progress id="ytBar"></progress>
    <span class="yt-timer">00:00</span>
    <span class="yt-button" onclick="ytDiv.pauseVideo()">STOP</span>
</div>
</div>

<script src="https://www.youtube.com/iframe_api"></script>
<script>
function onYouTubeIframeAPIReady() {
    ytDiv = new YT.Player(ytDiv.querySelector("iframe"));
    setInterval(() => {
        if (ytDiv.getCurrentTime() > 0) {
            document.querySelector("#ytDiv div").style.display = "block";
            document.querySelectorAll("#ytDiv div")[1].style.display = document.querySelectorAll("#ytDiv div")[2].style.display = "none";
            document.querySelector("#ytDiv iframe").style.top = "-150%";
            document.querySelector("#ytDiv iframe").style.height = "400%";
            playerDiv.style.display = "flex";
        }
        ytBar.value = Math.floor(ytDiv.getCurrentTime());
        ytBar.max = Math.floor(ytDiv.getDuration());
        document.querySelectorAll(".yt-timer")[0].innerText = ("0" + Math.floor(ytDiv.getCurrentTime() / 60)).slice(-2) + ":" + ("0" + Math.floor(ytDiv.getCurrentTime() % 60)).slice(-2);
        document.querySelectorAll(".yt-timer")[1].innerText = ("0" + Math.floor(ytDiv.getDuration() / 60)).slice(-2) + ":" + ("0" + Math.floor(ytDiv.getDuration() % 60)).slice(-2);
    }, 100);
}
ytBar.onclick = (e) => {
    ytDiv.seekTo(e.offsetX * ytBar.max / ytBar.offsetWidth);
    ytDiv.playVideo();
}
</script>

</body>

</html>
비타주리님 감사합니다! 제가 무지해서 ㅠㅠ 여태 컴터에서만 테스트 해봐서 안되었는데 웹서버에 올리고 테스트하니 잘 되는군요 ;;
추천드렸습니다. 아주 소중한 자료 감사합니다. 그리고 앞으로 잘사용하려고 합니다. 뷰에서는 정상으로 작동되구요. 리스트에서는 1개영상 올리면 잘되는데요. 혹시 1개이상 리스트에서는 안되는지요? 이상하게 안되네요. 공부하고 있지만 쉽지가 않습니다.ㅎㅎ
테스트 : https://wedgo1.cafe24.com/POTAL/bbs/board.php?bo_table=TOOPYO
링크보시면 2개인데 내용페이지에서는 잘되고 내용에서 다시 목록으로 빽하면 자동재생되면서 안되네요. 새로고침해도 영상은 정지하지만 스크립트 에러가 나요. ㅠ
전체 2,412 |RSS
그누보드5 팁자료실 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT