apple2js/js/ui/audio.js

90 lines
2.4 KiB
JavaScript
Raw Normal View History

2019-03-01 05:21:18 +00:00
/* Copyright 2010-2019 Will Scullin <scullin@scullinsteel.com>
2014-03-06 04:04:54 +00:00
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation. No representations are made about the suitability of this
* software for any purpose. It is provided "as is" without express or
* implied warranty.
*/
2019-03-01 05:21:18 +00:00
import { debug } from '../util';
2014-03-06 04:04:54 +00:00
/*
* Audio Handling
*/
2019-03-01 05:21:18 +00:00
export default function Audio(io) {
var sound = true;
var _samples = [];
2015-07-11 05:55:36 +00:00
var audioContext;
var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioNode;
var started = false;
2015-07-11 05:55:36 +00:00
if (AudioContext) {
audioContext = new AudioContext();
audioNode = audioContext.createScriptProcessor(4096, 1, 1);
2015-07-11 05:55:36 +00:00
audioNode.onaudioprocess = function(event) {
var data = event.outputBuffer.getChannelData(0);
var sample = _samples.shift();
var idx = 0;
2015-07-11 05:55:36 +00:00
var len = data.length;
if (sample) {
len = Math.min(sample.length, len);
for (; idx < len; idx++) {
data[idx] = sample[idx];
}
2016-11-22 05:17:34 +00:00
}
2015-07-11 05:55:36 +00:00
for (; idx < data.length; idx++) {
data[idx] = 0.0;
}
};
2015-07-11 05:55:36 +00:00
audioNode.connect(audioContext.destination);
}
2015-07-11 05:55:36 +00:00
function _initAudio(io) {
if (audioContext) {
debug('Using Webkit Audio');
io.sampleRate(audioContext.sampleRate);
io.addSampleListener(function(sample) {
if (sound) {
_samples.push(sample);
while (_samples.length > 5) {
_samples.shift();
}
2015-07-11 05:55:36 +00:00
}
});
}
2014-03-06 04:04:54 +00:00
}
_initAudio(io);
return {
autoStart: function () {
if (audioContext && !started) {
_samples = [];
audioContext.resume();
started = true;
}
},
start: function () {
if (audioContext) {
_samples = [];
audioContext.resume();
}
},
enable: function(enable) {
sound = enable;
}
};
2014-03-06 04:04:54 +00:00
}