LoginSignup
2
4

More than 5 years have passed since last update.

JavaScript Audio()で効果音をランダムに鳴らす

Last updated at Posted at 2014-12-01

Audio()コンストラクタを使えば、JavaScriptのみで音を鳴らせると聞いて、
サンプルを書いた。

var button = document.getElementById('button'),
    audioArr = [
      'audio/sample01.mp3',
      'audio/sample02.mp3',
      'audio/sample03.mp3',
      'audio/sample04.mp3'
    ];

var playAudio = function() {
  var audio = new Audio(),
      num = Math.floor(Math.random() * audioArr.length);

  if (num == audioArr.length) {
    num = audioArr.length - 1;
  }
  audio.src = audioArr[num];
  audio.play();
}

button.addEventListener('click', function() {
  playAudio();
}, false);
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4