본문 바로가기
D.evelop/MarkUp

video태그 - 자동 재생 autoplay에 대한 방법과 생각

by Danne 2022. 3. 15.

페이지에 접속함과 동시에 '영상이 자동재생'되게 해달라는 요청을 받았습니다. 

'autoplay넣으면 됐던거 같은데, 모바일에서는 자동재생 안됐던 것같은데?'등등의 기억을 더듬어 코드를 수정! 했으나 실패하여 0부터 다시 다 찾아봐야만했던 슬픈 이야기.

 

 

[처음 전달 받았던 코드의 ux flow]

1. 재생 버튼을 클릭하면
2. 영상이 담긴 레이어 팝업이 뜨면서
3. 해당 영상이 자동 재생된다.

 

[요청 사항]

1. 페이지 접속 시 메인화면 상단의 영상 자동 재생
2. 영상의 소리도 재생

 

[결론]

1. 자동 재생 시킴
2. 구글 정책 설명 후 소리 muted로 타협

 


 

 

1. 자동 재생 되지 않은 사례

<video class="video" autoplay controls>
    <source type="video/mp4" src="images/video.mp4" >
</video>

https://developer.chrome.com/blog/autoplay/

 

Autoplay policy in Chrome - Chrome Developers

Learn best practices for good user experiences with the new autoplay policies in Chrome.

developer.chrome.com

 

Chrome's autoplay policies are simple:
- Muted autoplay is always allowed.
- Autoplay with sound is allowed if:
   * The user has interacted with the domain (click, tap, etc.).

Chrome의 자동 재생 정책은 간단합니다.
- 음소거된 자동 재생은 항상 허용됩니다.
- 다음과 같은 경우 소리와 함께 자동 재생이 허용됩니다.
  * 사용자가 도메인과 상호작용했습니다(클릭, 탭 등).

출처 : chrome developer

 

즉,

자동재생 하지마라.

하려면 음소거를 해라.

 

 

 

2. 그래서 음소거 속성을 추가했습니다.

<video class="video" autoplay muted controls>
    <source type="video/mp4" src="images/video.mp4" >
</video>

 

 

3. 자동 재생이 됩니다. 다만 소리가 나오지 않네요. 

회사에서 요구한 거니까 일단 '시도'를 하는 모습이 필요합니다.

"사용자를 위한~~"등의 접근성에대한 마음은 잠시 접어두고요. 

 

💡 아이디어

일단 모든 DOM 요소가 로드되어 페이지에 안착했을때(video 태그의 랜더링이 완료되면)

슬며시 muted를 제거해보기로 했습니다.

 

🙋‍♀️ "소리 끈 video 입장이요~"

👨‍✈️ 통과!

🙋‍♀️"소리켠다"

 

<!--autoplay muted 뺌-->
<video class="video" controls>
    <source type="video/mp4" src="images/video.mp4" >
</video>

<script>
var video = document.querySelector(".video"); 
if(video.paused){ 
    setTimeout(function(){ 
        video.play();  
    }, 2000); // 2초 후 재생
}
</script>

결과

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first

출처 - Chrome Developers

DON'T!!!

 

 

4. "사용자가 도메인과 상호작용했습니다(클릭, 탭 등)"에 집중 해보기로했습니다.

:: "window가 로드 되는 걸 하나의 이벤트로 여겨볼텐가?"

<!--autoplay muted 뺌-->
<video class="video" controls>
    <source type="video/mp4" src="images/video.mp4" >
</video>

<script>
	// 윈도우 로드 이벤트시 video 재생
    window.addEventListener('load', function(){
      document.querySelector('.video').play();
    });
    
    /*
    window.onload = function() { 
    	// 코드 
    }
    */
</script>

결과

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first

 

:: "scroll이면 상호작용이겠지? 스크롤이 살짝! 됐을 때 재생기시키면 되겠지?"

<!--autoplay muted 뺌-->
<video class="video" controls>
    <source type="video/mp4" src="images/video.mp4" >
</video>

<script>
    window.addEventListener('scroll', function(e){
        console.log(e)
        document.querySelector('.video').play();
    });
</script>

결과

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first

이유?

"도메인에서의 사용자 상호 작용"으로 간주되는 것은 무엇입니까?  문서 자체를 클릭하면(스크롤링 제외) 사용자 상호작용으로 계산됩니다.

출처 - The Chomium Projects - autoplay

스크롤은 제외라네요.

 

안됩니다 안돼요

빈틈없이 다 잡아냅니다.

 

 

 

4. 공식문서에서 근접한 답을 찾았다.

https://developer.chrome.com/blog/autoplay/#audiovideo-elements

 

Autoplay policy in Chrome - Chrome Developers

Learn best practices for good user experiences with the new autoplay policies in Chrome.

developer.chrome.com

https://developers.google.com/web/updates/2016/03/play-returns-promise

 

HTMLMediaElement.play() Returns a Promise  |  Web  |  Google Developers

Say goodbye to automatic playback uncertainty! play() now returns a Promise.

developers.google.com

<!--autoplay muted 뺌-->
<video class="video" playsinline controls data-keepplaying>
    <source type="video/mp4" src="images/video.mp4" >
</video>

<script>
var autoplayVideoInterval = setInterval("autoplayVideo()",100);

function autoplayVideo(){
	var promise = document.querySelector('.video').play();
	if (promise !== undefined){	
		promise.then(_=>{
		clearInterval(autoplayVideoInterval);
	}).catch(error =>{
	});
	}
}
</script>

하지만 이 또한 간헐적으로 정지합니다.

때로는 스크롤을 다내리는 동안 정지해있다가, 화면 어딘가를 클릭해 주어야 재생됩니다.

 


 

[번외]

📍 fullpage.js 에서 영상 재생 유지하고 싶을 때

전달받은 소스의 레이아웃은 fullpage.js로 작성되어 있었습니다.

이때 다른 section으로 슬라이드가되면 비디오가 일시정지 됩니다.

페이지가 다른 슬라이드로 넘어가도 비디오의 재생을 유지하기 위해서는 data-keepplaying 속성을 넣어줍니다.

<video class="video" autoplay muted controls data-keepplaying>
    <source type="video/mp4" src="images/video.mp4" >
</video>

https://github.com/alvarotrigo/fullPage.js#pause-on-leave

 

GitHub - alvarotrigo/fullPage.js: fullPage plugin by Alvaro Trigo. Create full screen pages fast and simple

fullPage plugin by Alvaro Trigo. Create full screen pages fast and simple - GitHub - alvarotrigo/fullPage.js: fullPage plugin by Alvaro Trigo. Create full screen pages fast and simple

github.com

 

📍 playsinline

ios(아이폰 등)에서 video재생버튼 선택 시 전체화면으로 재생되는 것을 방지하려면 playsinline속성을 넣어준다.

playsinline 
비디오가 요소의 재생 영역 내에서 "인라인"으로 재생됨을 나타내는 부울 속성입니다.
이 속성이 없다고 해서 비디오가 항상 전체 화면으로 재생된다는 의미는 아닙니다.

 

참고 : Autoplaying inline videos on iPhone iOS 10 using Angular - Abou Kone

 

 

📍 시도했으나 안된 것들

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_av_prop_muted 

 

W3Schools online HTML editor

The W3Schools online code editor allows you to edit code and view the result in your browser

www.w3schools.com

 


 

[마무리]

 

😅 처음 전달 받은 코드에서는 왜 되었던가?

"1. 재생 버튼을 클릭하면" 이라는 트리거가 있었다.

 

 

😅 크롬을 포기할 게 아니면 구글이 시키는 대로 하자.

무려 chromium 프로젝트에서 공시한 사항이니, 무시하면 SEO 불리해질 수 있지 않을까? 그건 아니다.

자동 재생을 드물게 사용합니다. 자동 재생은 강력한 참여 도구가 될 수 있지만 원치 않는 사운드가 재생되거나 원치 않는 비디오 재생의 결과로 불필요한 리소스 사용(예: 데이터, 배터리)을 인식하는 경우 사용자를 짜증나게 할 수도 있습니다. 
출처 : The Chromium Projects

 

구글 SEO자체에는 불리함을 주지 않지만 비슷한 의견을 찾았다. 
https://www.quora.com/Are-videos-that-auto-play-good-or-bad-for-SEO

It’s a bad user experience and SEO is valuing user experience more and more. If someone comes to the site and a video starts autoplaying, they are more likely to click out, increasing bounce rate which has a negative impact on SEO. - Mariachiara Marsella
(그것은 나쁜 사용자 경험이며 SEO는 사용자 경험을 점점 더 중요하게 생각합니다. 
누군가가 사이트에 와서 비디오가 자동 재생을 시작하면 클릭할 가능성이 높아져 이탈률이 증가하여 SEO에 부정적인 영향을 미칩니다.

'그럼에도 SEO 사용자 경험을 더욱 충족하는 방향으로 발전 한다.'


'자동 재생되는 페이지 = 안좋은 사용자 경험. 결국 이탈률을 야기시킨다.
이탈률이 많은 페이지 = SEO에 부정적인 영향'

 

참고해보면 좋을 Chorme의 더 나은 광고 표준 (Coalition for Better Ads)

It Hurts Accessibility
Believe it or not, there are people with visual impairments who browse the internet. People without handicaps don’t tend to think about the people who do, and it can cause a significant loss of reputation, traffic, or just accessibility.
(믿거나 말거나 인터넷을 검색하는 시각 장애가 있는 사람들이 있습니다. 핸디캡이 없는 사람들은 장애가 있는 사람들에 대해 생각하지 않는 경향이 있으며, 이는 평판, 트래픽 또는 접근성에 상당한 손실을 초래할 수 있습니다.)

출처 : SEOblog

 

 

 

 

 

 

[참고]

MDN - <video>: 비디오 삽입 요소

https://developer.mozilla.org/ko/docs/Web/HTML/Element/Video

 

MDN - 미디어 및 Web Audio API 자동 재생 가이드

https://developer.mozilla.org/ko/docs/Web/Media/Autoplay_guide


The Chomium Projects
https://sites.google.com/a/chromium.org/dev/audio-video/autoplay

 

Chrome Developers - Autoplay policy in Chrome

https://developer.chrome.com/blog/autoplay/

 

Chrome Developers - DOMException: The play() request was interrupted
https://developers.google.com/web/updates/2017/06/play-request-was-interrupted

블로그 - <video>태그 브라우저, 모바일 이슈 정리 사항

반응형

댓글