Skip to content

Instantly share code, notes, and snippets.

@kuu
Created February 19, 2014 04:00
Show Gist options
  • Save kuu/9085844 to your computer and use it in GitHub Desktop.
Save kuu/9085844 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=yes" />
</head>
<body>
<button id="loadBGMBtn">Load BGM</button>
<button id="loadSEBtn">Load SE</button>
<button id="playBGMBtn">Play BGM</button>
<button id="playSEBtn">Play SE</button>
<div id="Message"></div>
<script>
document.addEventListener("DOMContentLoaded", function() {
var tLoadBGMButton = document.getElementById('loadBGMBtn');
var tLoadSEButton = document.getElementById('loadSEBtn');
var tPlayBGMButton = document.getElementById('playBGMBtn');
var tPlaySEButton = document.getElementById('playSEBtn');
var tMessage = document.getElementById('Message');
var AudioContext = window.AudioContext || window.webkitAudioContext;
if (!AudioContext) {
tMessage.innerHTML = 'Web Audio API is not supported.';
return;
}
var tContext = new AudioContext();
var tSEBuffer, tBGMBuffer;
var tSE, tBGM;
// Load BGM.
tLoadBGMButton.addEventListener('click', function () {
var tXHR = new XMLHttpRequest();
tXHR.open('GET', 'bgm.mp3');
tXHR.responseType = 'arraybuffer';
tXHR.onreadystatechange = function() {
if (tXHR.readyState === 4 && tXHR.status === 200) {
tContext.decodeAudioData(
tXHR.response,
function (pAudioBuffer) {
tMessage.innerHTML += 'BGM loaded.';
tBGMBuffer = pAudioBuffer;
},
function () {
tMessage.innerHTML += 'Failed to load BGM.';
}
);
}
};
tXHR.send();
}, false);
// Load SE.
tLoadSEButton.addEventListener('click', function () {
var tXHR = new XMLHttpRequest();
tXHR.open('GET', 'fire.wav');
tXHR.responseType = 'arraybuffer';
tXHR.onreadystatechange = function() {
if (tXHR.readyState === 4 && tXHR.status === 200) {
tContext.decodeAudioData(
tXHR.response,
function (pAudioBuffer) {
tMessage.innerHTML += 'SE loaded.';
tSEBuffer = pAudioBuffer;
},
function () {
tMessage.innerHTML += 'Failed to load SE.';
}
);
}
};
tXHR.send();
}, false);
// Play BGM
tPlayBGMButton.addEventListener('click', function (e) {
if (tBGM) {
tBGM.disconnect();
}
tBGM = tContext.createBufferSource();
tBGM.buffer = tBGMBuffer;
tBGM.connect(tContext.destination);
if (tBGM.start) {
tBGM.start(0, 5.5);
} else {
tBGM.noteGrainOn(0, 5.5, tBGMBuffer.duration);
}
}, false);
// Play SE
tPlaySEButton.addEventListener('click', function (e) {
if (tSE) {
tSE.disconnect();
}
tSE = tContext.createBufferSource();
tSE.buffer = tSEBuffer;
tSE.connect(tContext.destination);
if (tSE.start) {
tSE.start(0);
} else {
tSE.noteOn(0);
}
}, false);
}, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment