Skip to content

Commit 5942a8b

Browse files
authored
Merge pull request #2436 from mysubcult/feat/voice-record-at-once
Voice message: start recording at once and show the input level
2 parents adc5eff + edd21a3 commit 5942a8b

2 files changed

Lines changed: 144 additions & 14 deletions

File tree

‎lhc_web/design/defaulttheme/css/widgetv2/widget.css‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1194,6 +1194,26 @@ a.btn-link.visited{
11941194
padding-bottom: 8px;
11951195
}
11961196

1197+
/* Voice message: live input level while recording (VoiceMessage.js moves the bars) */
1198+
.voice-message-level{
1199+
display: inline-flex;
1200+
align-items: center;
1201+
gap: 2px;
1202+
height: 20px;
1203+
margin: 0 4px;
1204+
vertical-align: middle;
1205+
}
1206+
1207+
.voice-message-level i{
1208+
display: block;
1209+
width: 3px;
1210+
height: 100%;
1211+
border-radius: 2px;
1212+
background-color: currentColor;
1213+
transform: scaleY(0.12);
1214+
transition: transform .08s linear;
1215+
}
1216+
11971217
.content-loader {
11981218
background: url(../images/icons/loading.png) no-repeat center center;
11991219
}

‎lhc_web/design/defaulttheme/widget/react-app/src/components/VoiceMessage.js‎

Lines changed: 124 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,6 @@ import React, { PureComponent } from 'react';
22
import vmsg from "vmsg";
33
import { withTranslation } from 'react-i18next';
44

5-
const recorder = new vmsg.Recorder({
6-
wasmURL: window.lhcChat['staticJS']['chunk_js']+ "/" + 'vmsg.8c4a15f2.wasm',
7-
shimURL: "https://unpkg.com/wasm-polyfill.js@0.2.0/wasm-polyfill.js"
8-
});
9-
105
class VoiceMessage extends PureComponent {
116

127
state = {
@@ -21,6 +16,15 @@ class VoiceMessage extends PureComponent {
2116

2217
constructor(props) {
2318
super(props);
19+
// A reopened panel must not share a pending microphone request with the old one.
20+
this.recorder = new vmsg.Recorder({
21+
wasmURL: window.lhcChat['staticJS']['chunk_js']+ "/" + 'vmsg.8c4a15f2.wasm',
22+
// No external WebAssembly polyfill. Without usable WebAssembly the worker
23+
// fails to initialize and the "not supported" message is shown.
24+
shimURL: "data:text/javascript,"
25+
});
26+
this.isUnmounted = false;
27+
this.recordingStarting = false;
2428
this.startRecording = this.startRecording.bind(this);
2529
this.stopRecording = this.stopRecording.bind(this);
2630
this.playRecord = this.playRecord.bind(this);
@@ -31,6 +35,12 @@ class VoiceMessage extends PureComponent {
3135
this.stopWebkitRecording = this.stopWebkitRecording.bind(this);
3236
this.toggleWebkitRecording = this.toggleWebkitRecording.bind(this);
3337

38+
// Live input level while recording (bars in .voice-message-level)
39+
this.levelRef = React.createRef();
40+
this.levelAnalyser = null;
41+
this.levelFrame = null;
42+
this.levelHistory = [];
43+
3444
// Intervals
3545
this.durationInterval = null;
3646
this.playInterval = null;
@@ -75,13 +85,25 @@ class VoiceMessage extends PureComponent {
7585
}
7686

7787
async startRecording() {
88+
if (this.isUnmounted || this.recordingStarting || this.state.isRecording) {
89+
return;
90+
}
91+
this.recordingStarting = true;
7892
this.stopPlayRecord();
7993
this.setState({ isLoading: true, audioDuration : 0, recording: null, isPlaying: false, currentTime : 0});
8094
try {
81-
await recorder.initAudio();
82-
await recorder.initWorker();
83-
recorder.startRecording();
84-
this.setState({ isLoading: false, isRecording: true });
95+
await this.recorder.initAudio();
96+
if (this.isUnmounted) {
97+
this.closeRecorder();
98+
return;
99+
}
100+
await this.recorder.initWorker();
101+
if (this.isUnmounted) {
102+
this.closeRecorder();
103+
return;
104+
}
105+
this.recorder.startRecording();
106+
this.setState({ isLoading: false, isRecording: true }, () => this.startLevelMeter());
85107
this.durationInterval = setInterval(() => {
86108
this.setState({ audioDuration: this.state.audioDuration + 1 });
87109

@@ -92,13 +114,94 @@ class VoiceMessage extends PureComponent {
92114

93115
}, 1000);
94116
} catch (e) {
117+
this.closeRecorder();
118+
if (this.isUnmounted) {
119+
return;
120+
}
95121
alert('Sorry but voice messages are not supported on your browser!');
96122
this.setState({ isLoading: false });
123+
} finally {
124+
this.recordingStarting = false;
125+
}
126+
}
127+
128+
closeRecorder() {
129+
// stopRecording() may already have closed the AudioContext.
130+
if (this.recorder.audioCtx && this.recorder.audioCtx.state === 'closed') {
131+
this.recorder.audioCtx = null;
132+
}
133+
this.recorder.close();
134+
this.recorder.audioCtx = null;
135+
}
136+
137+
startLevelMeter() {
138+
this.stopLevelMeter();
139+
try {
140+
if (!this.recorder.audioCtx || !this.recorder.gainNode || typeof this.recorder.audioCtx.createAnalyser !== 'function') {
141+
return;
142+
}
143+
const analyser = this.recorder.audioCtx.createAnalyser();
144+
analyser.fftSize = 512;
145+
this.recorder.gainNode.connect(analyser);
146+
this.levelAnalyser = analyser;
147+
} catch (e) {
148+
return;
149+
}
150+
151+
const samples = new Uint8Array(this.levelAnalyser.fftSize);
152+
let lastSample = 0;
153+
154+
const draw = (time) => {
155+
if (this.levelAnalyser === null) {
156+
return;
157+
}
158+
// A new bar every 80ms, like a waveform moving to the left
159+
if (time - lastSample >= 80) {
160+
lastSample = time;
161+
this.levelAnalyser.getByteTimeDomainData(samples);
162+
let sum = 0;
163+
for (let i = 0; i < samples.length; i++) {
164+
const v = (samples[i] - 128) / 128;
165+
sum += v * v;
166+
}
167+
const level = Math.min(1, Math.sqrt(sum / samples.length) * 4);
168+
const bars = this.levelRef.current ? this.levelRef.current.children : [];
169+
this.levelHistory.push(level);
170+
if (this.levelHistory.length > bars.length) {
171+
this.levelHistory.splice(0, this.levelHistory.length - bars.length);
172+
}
173+
const offset = bars.length - this.levelHistory.length;
174+
for (let i = 0; i < bars.length; i++) {
175+
const value = i >= offset ? this.levelHistory[i - offset] : 0;
176+
bars[i].style.transform = 'scaleY(' + Math.max(0.12, value).toFixed(3) + ')';
177+
}
178+
}
179+
this.levelFrame = window.requestAnimationFrame(draw);
180+
};
181+
182+
this.levelFrame = window.requestAnimationFrame(draw);
183+
}
184+
185+
stopLevelMeter() {
186+
if (this.levelFrame !== null) {
187+
window.cancelAnimationFrame(this.levelFrame);
188+
this.levelFrame = null;
189+
}
190+
if (this.levelAnalyser !== null) {
191+
try { this.recorder.gainNode.disconnect(this.levelAnalyser); } catch (e) {}
192+
try { this.levelAnalyser.disconnect(); } catch (e) {}
193+
this.levelAnalyser = null;
97194
}
195+
this.levelHistory = [];
98196
}
99197

100198
async stopRecording(){
101-
const blob = await recorder.stopRecording();
199+
clearInterval(this.durationInterval);
200+
this.stopLevelMeter();
201+
const blob = await this.recorder.stopRecording();
202+
if (this.isUnmounted) {
203+
return;
204+
}
102205

103206
this.audio = new Audio();
104207
this.audio.src = URL.createObjectURL(blob);
@@ -365,10 +468,16 @@ class VoiceMessage extends PureComponent {
365468
componentDidMount() {
366469
if (this.props.voice_engine == 1) {
367470
this.startWebkitRecording();
471+
} else {
472+
// The visitor already pressed "Record voice message" - start right away
473+
this.startRecording();
368474
}
369475
}
370476

371477
componentWillUnmount() {
478+
this.isUnmounted = true;
479+
clearInterval(this.durationInterval);
480+
clearInterval(this.playInterval);
372481

373482
// console.log('[VoiceMessage] componentWillUnmount()', {
374483
// isRecording: this.state.isRecording,
@@ -377,11 +486,10 @@ class VoiceMessage extends PureComponent {
377486

378487
// Stop playing if anything is playing
379488
this.stopPlayRecord();
489+
this.stopLevelMeter();
380490

381-
// Stop recording if it's recording
382-
if (this.state.isRecording) {
383-
recorder.stopRecording();
384-
}
491+
// Release microphone/worker even if initialization has not finished yet.
492+
this.closeRecorder();
385493

386494
// Stop webkit recognition if active
387495
if (this.recognition) {
@@ -430,6 +538,8 @@ class VoiceMessage extends PureComponent {
430538

431539
{recording && isPlaying === true && <button type="button" tabIndex="0" className="material-icons material-icons-button pointer text-success me-0 fs25" title={t('voice.stop_playing_recorded')} onClick={this.stopPlayRecord}>&#xf112;</button>}
432540

541+
{isRecording && <span className="voice-message-level" ref={this.levelRef} aria-hidden="true">{Array.from({length: 24}, (v, i) => <i key={i}></i>)}</span>}
542+
433543
<span className="fs12 px-1 voice-message-length">{isRecording ? '' : (isPlaying ? this.pad(this.state.currentTime) + ':' : '')}{isRecording || !recording ? (this.props.maxSeconds - this.state.audioDuration) + " s." : this.pad(this.state.audioDuration) + (!isPlaying ? 's.' : '')}</span>
434544

435545
{recording && <button type="button" tabIndex="0" className="material-icons material-icons-button pointer text-success me-0 fs25" title={t('voice.send')} onClick={this.sendRecord}>&#xf107;</button>}

0 commit comments

Comments
 (0)