Web Audio API는 사운드를 다루는 고급 기능입니다. audio 요소에 비해 기능이 많고 제약이 적습니다. 예를 들면 사운드 파형의 데이터를 가져와 비주얼라이저를 만들거나, 모바일 브라우저에서 여러 RGM과 효과음을 동시에 재생할 수 있었습니다. 다만 고급 기능이므로 난이도가 있고 코드가 길어집니다. 사운드 파일을 로딩하여 재생하는 샘플을 확인해볼 수 있습니다. loadAndPlay()함수를 사용해 사운드를 재생합니다.
실행하기 위해 라이브 서버로 사용해야 합니다. vscode 라이브 서버 확장 프로그램 다운 받아주시면 됩니다.
index.html
<div>
<button class="play">재생</button>
<button class="stop">정지</button>
</div>
script.js
const mp3Play = document.querySelector('.play');
const mp3Stop = document.querySelector('.stop');
mp3Play.addEventListener('click', loadAndPlay);
mp3Stop.addEventListener('click', stop);
console.log(mp3Play);
loadAndPlay();
let source;
async function loadAndPlay() { // 재생 처리
const context = new AudioContext();
const data = await fetch('music.mp3'); // 사운드 파일 로딩
const buffer = await data.arrayBuffer(); // arrayBuffer 사용
const decodedBuffer = await context.decodeAudioData(buffer); // 오디오 데이터 변환
source = context.createBufferSource(); // 소스 작성
source.buffer = decodedBuffer; // 소스에 오디오 데이터 할당
source.connect(context.destination); // 스피커 연결
source.start(0); // 재생 시작
}
function stop() { // 정지 기능
source.stop(); // 재생 정지
}