apple2js/js/ui/audio.js

94 lines
2.5 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
*/
2020-07-21 00:12:50 +00:00
var SAMPLE_SIZE = 1024;
var SAMPLE_RATE = 44000;
2020-07-21 00:04:55 +00:00
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) {
2020-07-21 00:04:55 +00:00
audioContext = new AudioContext({
sampleRate: SAMPLE_RATE
});
audioNode = audioContext.createScriptProcessor(SAMPLE_SIZE, 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');
2020-07-21 00:04:55 +00:00
io.sampleRate(audioContext.sampleRate, SAMPLE_SIZE);
io.addSampleListener(function(sample) {
if (sound) {
2020-07-21 00:04:55 +00:00
if (_samples.length < 5) {
_samples.push(sample);
}
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
}