Javascript

javascript - 배경음악 자동 재생하기

개발따라김양 2023. 2. 22. 16:02

1. 문제 상황

배경음악을 자동으로 재생하고 싶지만 

play() failed because the user didn't interact with the document first.

에러 발생

이 에러는 브라우저에서 자동재생을 방지하기 위해 최근에 도입된 정책 중 하나로 인해 발생함

 

2. 문제 해결

2-1. getUserMedia()로 사용자에게 권한을 받아오기

//js파일이나 script 태그

window.onload = function () {
  const bgSound = new Audio("배경음악 경로");
  navigator.mediaDevices
    .getUserMedia({ audio: true })
    .then(() => {
      let AudioContext = window.AudioContext;
      let audioContext = new AudioContext();
      playSound(bgSound);
    })
    .catch((e) => {
      console.error(`Audio permissions denied: ${e}`);
    });
};


function playSound(sound) {
  const bgsong = sound.play();
  sound.loop = true;
  if (bgsong !== undefined) {
    bgsong;
  }
}

 

2-2. embed 태그 활용하기

//html 파일

<embed src="음악경로" autostart="true" loop="infinite" width="0" height="0"></embed>

//width와 height를 0으로 지정하면 화면에 나오지 않음
//값을 지정해주면 크기만큼 나옴