Skip to content

Instantly share code, notes, and snippets.

@nummi
Last active November 13, 2016 21:47
Show Gist options
  • Select an option

  • Save nummi/ba540a82b2e776ed97229a31b7fd0430 to your computer and use it in GitHub Desktop.

Select an option

Save nummi/ba540a82b2e776ed97229a31b7fd0430 to your computer and use it in GitHub Desktop.
Feedback audio
<html>
<body>
<button onclick="window.feedbackAudio.success();">Success</button> &nbsp; | &nbsp;
<button onclick="window.feedbackAudio.attention();">Attention</button> &nbsp; | &nbsp;
<button onclick="window.feedbackAudio.sad();">Sad</button>
<script src="audio.js"></script>
</body>
</html>
(function() {
// http://marcgg.com/blog/2016/11/01/javascript-audio/
const audioInit = function audioInit() {
try {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
}
catch(e) {
// Web Audio API is not supported in this browser
}
};
const activeAudio = [];
let activeTone = null;
const play = function play(frequency, type='sine', maxGain=0.9) {
try {
const context = new window.AudioContext()
const oscil = context.createOscillator();
const gain = context.createGain();
gain.gain.value = 0.00001;
oscil.type = type;
oscil.connect(gain);
oscil.frequency.value = frequency;
gain.connect(context.destination);
oscil.start(0);
gain.gain.exponentialRampToValueAtTime(maxGain, context.currentTime + 0.2);
gain.gain.exponentialRampToValueAtTime(0.00001, context.currentTime + 1);
window.setTimeout(function() {
oscil.stop();
context.close();
}, 1000);
return {
gain, context, oscil
};
}
catch(e) {
console.log(e);
}
};
const success = function success() {
play(523.3, 'sine');
play(329.6, 'sine');
play(392.0, 'sine');
};
const attention = function attention() {
play(196.0, 'sine', 0.6);
play(392.0, 'sine', 0.6);
play(523.3, 'sine', 0.6)
};
const sad = function sad() {
setTimeout(function() {
play(58.27, 'triangle');
play(110.00, 'sine', 0.75);
}, 150);
play(220.00, 'triangle');
play(220.00, 'sine', 0.6);
};
window.feedbackAudio = {
success, attention, sad
};
window.addEventListener('load', audioInit, false);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment