Skip to content

Instantly share code, notes, and snippets.

@kuu
Created February 19, 2014 03:33
Show Gist options
  • Save kuu/9085585 to your computer and use it in GitHub Desktop.
Save kuu/9085585 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="loadBtn">Load</button>
<button id="playBtn">Play</button>
<button id="Up">Up</button>
<button id="Down">Down</button>
<div id="Message"></div>
<script>
document.addEventListener("DOMContentLoaded", function() {
var tLoadButton = document.getElementById('loadBtn');
var tPlayButton = document.getElementById('playBtn');
var tUpButton = document.getElementById('Up');
var tDownButton = document.getElementById('Down');
var tMessage = document.getElementById('Message');
var AudioContext = window.AudioContext || window.webkitAudioContext;
if (!AudioContext) {
tMessage.innerHTML = 'Web Audio API is not supported.';
}
var tContext = new AudioContext();
var tBuffer = null;
var tSource, tStartTime, tPlayedTime = 0, tOffset = 5.5;
var tGain = tContext.createGainNode();
tGain.connect(tContext.destination);
tLoadButton.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) {
console.log('decode success');
tBuffer = pAudioBuffer;
},
function () {
console.log('decode failure');
}
);
}
};
tXHR.send();
}, false);
tPlayButton.addEventListener('click', function (e) {
if (e.target.innerHTML === 'Play') {
tSource = tContext.createBufferSource();
tSource.buffer = tBuffer;
tSource.connect(tGain);
tStartTime = tContext.currentTime;
if (tSource.start) {
tSource.start(0, tOffset);
} else {
tSource.noteGrainOn(0, tOffset, tBuffer.duration);
}
e.target.innerHTML = 'Pause';
} else {
tPlayedTime = tContext.currentTime - tStartTime;
tOffset += tPlayedTime;
tSource.disconnect(tGain);
tSource = null;
e.target.innerHTML = 'Play';
}
}, false);
tUpButton.addEventListener('click', function () {
var tVol = tGain.gain.value + 0.1;
if (tVol <= 1) {
tGain.gain.value = tVol;
}
}, false);
tDownButton.addEventListener('click', function () {
var tVol = tGain.gain.value - 0.1;
if (tVol >= 0) {
tGain.gain.value = tVol;
}
}, false);
}, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment