반응형
Notice
Recent Posts
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Today
Total
관리 메뉴

오식랜드

[javascript] html 페이지에 bgm 추가하기 본문

dev-log/html·css·js

[javascript] html 페이지에 bgm 추가하기

개발하는 오식이 2021. 5. 21. 15:50
반응형

sound.js
0.00MB

bgm을 on/off 버튼으로 조작되도록 하자

sound.js(첨부파일)를 불러온 후 main.js에서 제어를 할 것이다.

html

<body>  
    <div class="soundIcon-wrapper">
        <button class="sound-icon" id="soundOff"></button>
        <button class="sound-icon" id="soundOn"></button>
    </div>  

    <script src="js/sound.js"></script>
    <script src="js/main.js"></script>
</body>

 

sound.js

우선은 sound.js를 확인해보자

내장 함수로 초기함수, 시작함수, 멈춤함수가 있고, 인자로는 id, source, volume, loop 네가지를 받는다.

<script>
function Sound(id,source,volume,loop)
{ ~
    this.init = function(){ ~ }
    this.startMusic = function(){ ~ } 
    this.pauseMusic = function(){ ~ } 
}
</script>

 

main.js

bgmPath : bgm의 링크

bgmNowPlaying : 재생/멈춤을 제어할 때 쓰일 boolean형태의 변수

bgm : sound.js의 Sound() 함수를 인스턴스로 불러온다 

 

불러온 후 초기 함수를 window가 로드되었을 때 실행시켜준다.

 

<script>
  var bgmPath = 'img/bgm.mp3';
  var bgmNowPlaying = false;
  var bgm = new Sound('myAudio', bgmPath, 100, true);

  window.onload = function() {
      bgm.init();
  };
</script>

 

bgm on/off 버튼 클릭 시 시작/멈춤 함수를 호출하자

bgm이 재생중일 땐 시작버튼이, 이미 멈춰있을 때 멈춤버튼이 클릭되지 않도록 bgmNowPlaying로 제어해주고, 

bgm의 내장함수인 startMusic()과 pauseMusic을 실행해주자

<script>
  var soundOff = document.getElementById('sound-off');
  var soundON = document.getElementById('sound-on');
  
  soundOff.addEventListener('click', bgmPlay);
  soundON.addEventListener('click', bgmStop);

  /**
   * 배경음 플레이
   */
  function bgmPlay() {
      if (!bgmNowPlaying) {
          bgmNowPlaying = !bgmNowPlaying;
          bgm.startMusic();
      }
  }

  /**
   * 배경음 일시 정지
   */
  function bgmStop() {
      if (bgmNowPlaying) {
          bgmNowPlaying = !bgmNowPlaying;
          bgm.pauseMusic();
      }
  }
  </script>
반응형
Comments