prefer native sample rate, if good - closes #201

This commit is contained in:
Jakob Ketterl 2021-04-29 16:23:51 +02:00
parent 7642341b2e
commit 7115d5c951

View File

@ -6,27 +6,15 @@ function AudioEngine(maxBufferLength, audioReporter) {
this.audioReporter = audioReporter; this.audioReporter = audioReporter;
this.initStats(); this.initStats();
this.resetStats(); this.resetStats();
var ctx = window.AudioContext || window.webkitAudioContext;
if (!ctx) {
return;
}
this.onStartCallbacks = []; this.onStartCallbacks = [];
this.started = false; this.started = false;
// try common working sample rates this.audioContext = this.buildAudioContext();
if (![48000, 44100].some(function(sr) { if (!this.audioContext) {
try { return;
this.audioContext = new ctx({sampleRate: sr});
return true;
} catch (e) {
return false;
}
}, this)) {
// fallback: let the browser decide
// this may cause playback problems down the line
this.audioContext = new ctx();
} }
var me = this; var me = this;
this.audioContext.onstatechange = function() { this.audioContext.onstatechange = function() {
if (me.audioContext.state !== 'running') return; if (me.audioContext.state !== 'running') return;
@ -43,6 +31,38 @@ function AudioEngine(maxBufferLength, audioReporter) {
this.maxBufferSize = maxBufferLength * this.getSampleRate(); this.maxBufferSize = maxBufferLength * this.getSampleRate();
} }
AudioEngine.prototype.buildAudioContext = function() {
var ctxClass = window.AudioContext || window.webkitAudioContext;
if (!ctxClass) {
return;
}
// known good sample rates
var goodRates = [48000, 44100]
// let the browser chose the sample rate, if it is good, use it
var ctx = new ctxClass();
if (goodRates.indexOf(ctx.sampleRate) >= 0) {
return ctx;
}
// if that didn't work, try if any of the good rates work
if (goodRates.some(function(sr) {
try {
ctx = new ctxClass({sampleRate: sr});
return true;
} catch (e) {
return false;
}
}, this)) {
return ctx;
}
// fallback: let the browser decide
// this may cause playback problems down the line
return new ctxClass();
}
AudioEngine.prototype.resume = function(){ AudioEngine.prototype.resume = function(){
this.audioContext.resume(); this.audioContext.resume();
} }