1
1
export class AudioHandler {
2
2
private context : AudioContext ;
3
+ private mergeNode : ChannelMergerNode ;
4
+ private analyserData : Uint8Array ;
5
+ public analyser : AnalyserNode ;
3
6
private workletNode : AudioWorkletNode | null = null ;
4
7
private stream : MediaStream | null = null ;
5
8
private source : MediaStreamAudioSourceNode | null = null ;
@@ -13,6 +16,16 @@ export class AudioHandler {
13
16
14
17
constructor ( ) {
15
18
this . context = new AudioContext ( { sampleRate : this . sampleRate } ) ;
19
+ // using ChannelMergerNode to get merged audio data, and then get analyser data.
20
+ this . mergeNode = new ChannelMergerNode ( this . context , { numberOfInputs : 2 } ) ;
21
+ this . analyser = new AnalyserNode ( this . context , { fftSize : 256 } ) ;
22
+ this . analyserData = new Uint8Array ( this . analyser . frequencyBinCount ) ;
23
+ this . mergeNode . connect ( this . analyser ) ;
24
+ }
25
+
26
+ getByteFrequencyData ( ) {
27
+ this . analyser . getByteFrequencyData ( this . analyserData ) ;
28
+ return this . analyserData ;
16
29
}
17
30
18
31
async initialize ( ) {
@@ -60,6 +73,7 @@ export class AudioHandler {
60
73
} ;
61
74
62
75
this . source . connect ( this . workletNode ) ;
76
+ this . source . connect ( this . mergeNode , 0 , 0 ) ;
63
77
this . workletNode . connect ( this . context . destination ) ;
64
78
65
79
this . workletNode . port . postMessage ( { command : "START_RECORDING" } ) ;
@@ -114,6 +128,7 @@ export class AudioHandler {
114
128
const source = this . context . createBufferSource ( ) ;
115
129
source . buffer = audioBuffer ;
116
130
source . connect ( this . context . destination ) ;
131
+ source . connect ( this . mergeNode , 0 , 1 ) ;
117
132
118
133
const chunkDuration = audioBuffer . length / this . sampleRate ;
119
134
0 commit comments