howler를 이용한 sound 제어
사운드 제어용으로 많이 사용하는 howler를 angular에서 사용하는 방식등에 대해 설명드리려고 합니다.
install
npm i howler
npm install --save-dev @types/howler
How to Use
Import
import { Howl } from 'howler';
사운드 설정
const effectSound = new Howl({
src: ['assets/sounds/effect.mp3'],
preload: true,
// html5: true,
onloaderror: (id, err) => {
console.warn('load effect.mp3 error', { id, err });
},
});
사운드 플레이
moveSound.play();
bgm 제어
bgm으로 사용할 경우는 중지할 때를 위해 play시 ID를 받아 와야 한다.
const bgmSound = new Howl({
src: ['assets/sounds/bgm.ogg'],
preload: true,
loop: true, // loop를 true로 설정하여 연속적인 실행을 가능하게 한다.
// html5: true,
volume: 0.5,
onloaderror: (id, err) => {
console.warn('load bgm.ogg error', { id, err });
},
});
let bgmSoundId;
bgmSound.once('load', () => { // 로드가 완료되면 바로 플레이 한다.
bgmSoundId = bgmSound.play();
});
// 중지시킬경우는 bgmSoundId 를 활용하여 처리한다.
bgmSound.stop(bgmSoundId);