Audio でサウンド再生
JavaScript から HTML5 の Audio 要素を再生するプログラムを作りました。囲碁のプログラムで使う3つの効果音(着手のときの音、ボタンを押したときの音、エラー時の音)を再生できます。
実行結果
ソース
ボタンを連続して押しても音が鳴るように、サウンド再生後に Audio 要素のオブジェクトを作り直しています。
sound.jp
var $classAll = function(c) { return document.getElementsByClassName(c); };
// ブラウザ対応拡張子取得
var AUDIO_EXT = (function(){
var ext = "";
var audio = new Audio();
if (audio.canPlayType("audio/ogg") == 'maybe') { ext="ogg"; }
else if (audio.canPlayType("audio/mp3") == 'maybe') { ext="mp3"; }
else if (audio.canPlayType("audio/wav") == 'maybe') { ext="wav"; }
return ext;
})();
// あらかじめ読み込んでおく
var AUDIO_LIST = {
"se00": new Audio("se/button6." + AUDIO_EXT),
"se01": new Audio("se/se_sad05." + AUDIO_EXT),
"se02": new Audio("se/se_sad08." + AUDIO_EXT),
};
// 初期化
window.onload = function() {
// Circle 要素取得
var eCircleList = $classAll("circle");
for (i=0, len=eCircleList.length; i<len; i++) {
var eCircle = eCircleList[i];
// クリックイベント登録
eCircle.addEventListener("click", function(){
var id = this.getAttribute("id");
// サウンド再生
AUDIO_LIST[id].play();
// 次呼ばれた時用に新たに生成
AUDIO_LIST[id] = new Audio(AUDIO_LIST[id].src);
}, false);
};
};
sound.html
<h2>実行結果</h2>
<div id="contents">
<div class="circle" id="se00">Click</div>
<div class="circle" id="se01">Switch</div>
<div class="circle" id="se02">Error</div>
</div><!-- end of contents -->
sound.css
@CHARSET "UTF-8";
#contents {
display: -webkit-box;
display: -moz-box;
display: -o-box;
display: box;
}
.circle {
margin: 10px;
width: 100px;
height: 100px;
border-radius: 50px;
color: white;
font-size: 20px;
text-align: center;
line-height: 100px;
box-shadow: 2px 2px 4px 0px #444;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
}
.circle:active {
box-shadow: inset 2px 2px 4px 0px #000;
}
.circle:nth-of-type(1) {
color: black;
background-color: white
}
.circle:nth-of-type(2) {
background-color: gray
}
.circle:nth-of-type(3) {
background-color: red
}