[드럼만들기] 유사배열객체

youngseo·2022년 3월 2일
0

JS프로젝트

목록 보기
10/18
post-thumbnail

드럼만들기

1. get, getAll 변수 만들기

;(function () {
  'use strict'
  
  const get = function (target) {
    return document.querySelector(target)
  }

  const getAll = function (target) {
    return document.querySelectorAll(target)
  }
  
  const init = () => {}
  
  init()
})()

2. soundRoot, drumSound

  const soundsRoot = 'assets/sounds/'
  const drumSounds = [
    { key: 81, sound: 'clap.wav' },
    { key: 87, sound: 'crash.wav' },
    { key: 69, sound: 'hihat.wav' },
    { key: 65, sound: 'kick.wav' },
    { key: 83, sound: 'openhat.wav' },
    { key: 68, sound: 'ride.wav' },
    { key: 90, sound: 'shaker.wav' },
    { key: 88, sound: 'snare.wav' },
    { key: 67, sound: 'tom.wav' },
  ]

keycode

https://keycode.info/

  • 키보드 입력으로 keycode를 알 수 있는 사이트

3. 유새배열객체를 배열로 받기

  //const keys2 = getAll('.key') 유사배열 객체임으로 Array.from 를 이용해 객체로 만들어줘야한다.
  const keys = Array.from(getAll('.key'))

4. audio엘레멘트리 생성

  const getAudioElement = (index) => {
    //DOM객체 생성
    const audio = document.createElement('audio')
    audio.dataset.key = drumSounds[index].key
    audio.src = soundsRoot + drumSounds[index].sound
    return audio
  }
  
   const init = () => {
    keys.forEach((key, index) => {  
      const audio = getAudioElement(index)
      //audio를 원하는 위치에 삽입
      key.appendChild(audio)
      key.dataset.key = drumSounds[index].key
    });
  }

5. 키보드 입력시 소리출력 설정

  const playSound = (keyCode) => {
    const $audio = get(`audio[data-key="${keyCode}"]`) //key가 keyCode와 동일한 경우 가져옴
    if($audio) {
      $audio.currentTime = 0
      $audio.play()
    }
  }

  const onKeyDown = (e) => {
    playSound(e.keyCode)
  }
  
  const init = () => {
    window.addEventListener('keydown', onKeyDown)  --(1)
      });
  }

keycode

6. 마우스 클릭 시 소리출력 설정

 const onMounseDown = (e) => {
    const keycode = e.target.getAttribute('data-key')
    playSound(keycode)
  }
  
  const init = () => {
	...
      key.addEventListener('click', onMounseDown)
    });
  }

7. 클릭하거나 키보드 입력시 애니메이션 효과

7-1 오디호 출력시 playing 클래스 추가하기

  const playSound = (keyCode) => {
    const $audio = get(`audio[data-key="${keyCode}"]`) //key가 keyCode와 동일한 경우 가져옴
    const $key = get(`div[data-key="${keyCode}"]`)
    if ($key && $audio) {
      $key.classList.add('playing')
      $audio.currentTime = 0
      $audio.play()
    }
  }

7-2 효과 후 playing 클래스 제거

  const ontransitionend = (e) => {
    if(e.propertyName === 'transform') {
      e.target.classList.remove('playing')
    }
  }
  
  const init = () => {
	...
      key.addEventListener('transitionend', ontransitionend)
    });
  }
  

0개의 댓글