Using "standardized-audio-context" to fix compatibility of AudioContext with Safari.

This commit is contained in:
David Négrier 2021-06-02 17:58:58 +02:00
parent d43633e936
commit 100198b55c
6 changed files with 41 additions and 61 deletions

View file

@ -1,3 +1,5 @@
import type {IAnalyserNode, IAudioContext, IMediaStreamAudioSourceNode} from 'standardized-audio-context';
/**
* Class to measure the sound volume of a media stream
*/
@ -5,10 +7,10 @@ export class SoundMeter {
private instant: number;
private clip: number;
//private script: ScriptProcessorNode;
private analyser: AnalyserNode|undefined;
private analyser: IAnalyserNode<IAudioContext>|undefined;
private dataArray: Uint8Array|undefined;
private context: AudioContext|undefined;
private source: MediaStreamAudioSourceNode|undefined;
private context: IAudioContext|undefined;
private source: IMediaStreamAudioSourceNode<IAudioContext>|undefined;
constructor() {
this.instant = 0.0;
@ -16,7 +18,7 @@ export class SoundMeter {
//this.script = context.createScriptProcessor(2048, 1, 1);
}
private init(context: AudioContext) {
private init(context: IAudioContext) {
this.context = context;
this.analyser = this.context.createAnalyser();
@ -25,7 +27,7 @@ export class SoundMeter {
this.dataArray = new Uint8Array(bufferLength);
}
public connectToSource(stream: MediaStream, context: AudioContext): void
public connectToSource(stream: MediaStream, context: IAudioContext): void
{
if (this.source !== undefined) {
this.stop();
@ -85,56 +87,3 @@ export class SoundMeter {
}
// Meter class that generates a number correlated to audio volume.
// The meter class itself displays nothing, but it makes the
// instantaneous and time-decaying volumes available for inspection.
// It also reports on the fraction of samples that were at or near
// the top of the measurement range.
/*function SoundMeter(context) {
this.context = context;
this.instant = 0.0;
this.slow = 0.0;
this.clip = 0.0;
this.script = context.createScriptProcessor(2048, 1, 1);
const that = this;
this.script.onaudioprocess = function(event) {
const input = event.inputBuffer.getChannelData(0);
let i;
let sum = 0.0;
let clipcount = 0;
for (i = 0; i < input.length; ++i) {
sum += input[i] * input[i];
if (Math.abs(input[i]) > 0.99) {
clipcount += 1;
}
}
that.instant = Math.sqrt(sum / input.length);
that.slow = 0.95 * that.slow + 0.05 * that.instant;
that.clip = clipcount / input.length;
};
}
SoundMeter.prototype.connectToSource = function(stream, callback) {
console.log('SoundMeter connecting');
try {
this.mic = this.context.createMediaStreamSource(stream);
this.mic.connect(this.script);
// necessary to make sample run, but should not be.
this.script.connect(this.context.destination);
if (typeof callback !== 'undefined') {
callback(null);
}
} catch (e) {
console.error(e);
if (typeof callback !== 'undefined') {
callback(e);
}
}
};
SoundMeter.prototype.stop = function() {
this.mic.disconnect();
this.script.disconnect();
};
*/