From bdbfa902fb78d836e2955366327b0fb3ec9dbefa Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Tue, 10 Apr 2018 14:20:27 +0200 Subject: [PATCH] [lib.audio-manager] added dynamic mic volume --- parcel/lib/audio-manager.js | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/parcel/lib/audio-manager.js b/parcel/lib/audio-manager.js index e32ed3f..13b206c 100644 --- a/parcel/lib/audio-manager.js +++ b/parcel/lib/audio-manager.js @@ -13,7 +13,8 @@ export default class AudioManager{ /* (2) Create the MASTER gain */ this.master = this.ctx.createGain(); this.volume = this.ctx.createGain(); - this.volume.gain.setValueAtTime(.65, 0); // input volume 65% + this.peaks = { low: 0, high: 0 }; + this.volume_value = 1; /* (3) Initialise input (typically bound from recorder) */ this.input = null; @@ -61,8 +62,8 @@ export default class AudioManager{ /* (7) Initialise coordinator to manage received */ this.stack = []; this.stack_size = 2; - this.fade_in = 0.1; - this.fade_out = 0.1; + this.fade_in = 0.1; + this.fade_out = 0.1; @@ -225,11 +226,24 @@ export default class AudioManager{ _audioprocess.inputBuffer.copyFromChannel(buf32, 0); /* (4) Convert for WS connection (Int16Array) */ + this.peaks.low = 0; + this.peaks.high = 0; let buf16 = this.f32toi16(buf32); /* (5) Send buffer through websocket */ this.ws.send(buf16); + /* (5) Adapt microphone volume if had peaks */ + if( this.peaks.high > .01 ) // 30% saturation -> decrease + this.volume_value *= .8; + + else if( this.peaks.low > .99 && this.volume_value*1.01 < 1 ) // 90% too low volume + less than 30% saturation -> increase + this.volume_value *= 1.01; + + // apply new volume + this.volume.gain.setValueAtTime(this.volume_value, this.ctx.currentTime); + + /* (2) WebSocket buffer stack read @@ -339,8 +353,15 @@ export default class AudioManager{ let i = 0, l = buf32.length; /* (3) Convert each value */ - for( ; i < l ; i++ ) + for( ; i < l ; i++ ){ buf16[i] = (buf32[i] < 0) ? 0x8000 * buf32[i] : 0x7FFF * buf32[i]; + ( buf32[i] > 0.9 ) && ( this.peaks.high++ ); + ( buf32[i] < 0.1 ) && ( this.peaks.low++ ); + } + + /* (4) Report peaks in percentage */ + this.peaks.high /= l; + this.peaks.low /= l; return buf16; }