@@ -8,15 +8,18 @@ export class RNSpeechDetector {
8
8
private pc1 = new RTCPeerConnection ( { } ) ;
9
9
private pc2 = new RTCPeerConnection ( { } ) ;
10
10
private intervalId : NodeJS . Timeout | undefined ;
11
+ private audioStream : MediaStream | undefined ;
11
12
12
13
/**
13
14
* Starts the speech detection.
14
15
*/
15
16
public async start ( ) {
16
17
try {
18
+ this . cleanupAudioStream ( ) ;
17
19
const audioStream = await navigator . mediaDevices . getUserMedia ( {
18
20
audio : true ,
19
21
} ) ;
22
+ this . audioStream = audioStream ;
20
23
21
24
this . pc1 . addEventListener ( 'icecandidate' , async ( e ) => {
22
25
await this . pc2 . addIceCandidate (
@@ -55,6 +58,7 @@ export class RNSpeechDetector {
55
58
public stop ( ) {
56
59
this . pc1 . close ( ) ;
57
60
this . pc2 . close ( ) ;
61
+ this . cleanupAudioStream ( ) ;
58
62
if ( this . intervalId ) {
59
63
clearInterval ( this . intervalId ) ;
60
64
}
@@ -97,4 +101,18 @@ export class RNSpeechDetector {
97
101
clearInterval ( this . intervalId ) ;
98
102
} ;
99
103
}
104
+
105
+ private cleanupAudioStream ( ) {
106
+ if ( ! this . audioStream ) {
107
+ return ;
108
+ }
109
+ this . audioStream . getTracks ( ) . forEach ( ( track ) => track . stop ( ) ) ;
110
+ if (
111
+ // @ts -expect-error release() is present in react-native-webrtc
112
+ typeof this . audioStream . release === 'function'
113
+ ) {
114
+ // @ts -expect-error called to dispose the stream in RN
115
+ this . audioStream . release ( ) ;
116
+ }
117
+ }
100
118
}
0 commit comments