본문 바로가기

WEB

[JavaScript] audio를 사용하는 방법들 / currentTime / play

audio를 사용해봅시다 😃


html은 오디오 객체를 지원합니다. 오늘은 이 오디오 객체를 조작하는 다양한 방법에 대해 알아보려고 합니다.

<audio id="one" controls></audio>

  1. html에서 제공하는 오디오 버튼을 사용하여 재생하는 방법
  2. 버튼을 생성하여 재생하는 방법
  3. 키보드를 사용하여 재생하는 방법

이렇게 3가지를 알아보겠습니다!

 


1. html에서 제공하는 오디오 버튼을 사용하여 재생

<audio id="one" src="sounds/piano.mp3" controls></audio>

html에서 제공하는 버튼을 사용하려면 src에 재생하고자하는 소리를 넣어주면 됩니다.


2. 버튼을 생성하여 재생

버튼을 사용하여 html에서 src에 넣은 소리를 다시 재생할 수 있는 방법이 있고 새로운 소리를 재생할 수 도 있습니다.

let pianoSound = document.querySelector("#one"); // html 상의 소리 재생

let pianoSound2 = new Audio("sounds/piano.mp3"); // html와 같은 소리지만 새로운 객체를 만들어서 재생

let laserSound = new Audio("sounds/laser1.wav"); // 새로운 소리 만들기

document.querySelector("#myBtn").addEventListener("click",function(){
      //빠르게 처음부터 다시 재생하고 싶다면
      pianoSound.currentTime=0;
      pianoSound.play();
});

currentTime은 원하는 시간을 넣어줍니다. 0으로 지정하면 처음으로 돌아갑니다.

play로 지정한 위치에서 재생시킬 수 있습니다.

 


3. 키보드를 사용하여 재생

//스페이스바를 눌렀을때 레이저 소리를 재생해 보세요.
document.querySelector("body").addEventListener("keydown",function(e){
      //e는 key 이벤트 객체이다.
      console.log(e);
      if(e.keyCode == 32){
            laserSound.currentTime=0;
            laserSound.play();
      }

});

키보드의 키의 움직임을 감지하는 방법은 body의 참조값을 받아오면됩니다.

스페이스바 키는 keyCode가 32번입니다.

눌러진 키의 코드가 32번일때 play해주면됩니다.


[전체코드]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Step13_audio.html</title>
</head>
<body>
    <h1>오디오 재생연습</h1>
    <audio id="one" src="sounds/piano.mp3" controls></audio>
    <button id="myBtn">눌러보셈</button>
    <script>
        let pianoSound = document.querySelector("#one");

        let pianoSound2 = new Audio("sounds/piano.mp3");

        let laserSound = new Audio("sounds/laser1.wav");

        document.querySelector("#myBtn").addEventListener("click",function(){
            //빠르게 처음부터 다시 재생하고 싶다면
            pianoSound.currentTime=0;
            pianoSound.play();
        });

        //스페이스바를 눌렀을때 레이저 소리를 재생해 보세요.
        document.querySelector("body").addEventListener("keydown",function(e){
            //e는 key 이벤트 객체이다.
            console.log(e);
            if(e.keyCode == 32){
                laserSound.currentTime=0;
                laserSound.play();
            }

        });
    </script>
</body>
</html>