Skip to content

Commit 3b1a54d

Browse files
authored
fix(record): release mic resources after recording (#4179)
1 parent 1e6e406 commit 3b1a54d

File tree

1 file changed

+20
-9
lines changed

1 file changed

+20
-9
lines changed

src/plugins/record.ts

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,9 @@ class RecordPlugin extends BasePlugin<RecordPluginEvents, RecordPluginOptions> {
6464
private lastStartTime = 0
6565
private lastDuration = 0
6666
private duration = 0
67+
private micStream: MicStream | null = null
68+
private unsubscribeDestroy?: () => void
69+
private unsubscribeRecordEnd?: () => void
6770

6871
/** Create an instance of the Record plugin */
6972
constructor(options: RecordPluginOptions) {
@@ -193,15 +196,16 @@ class RecordPlugin extends BasePlugin<RecordPluginEvents, RecordPluginOptions> {
193196

194197
const intervalId = setInterval(drawWaveform, 1000 / FPS)
195198

199+
const cleanup = () => {
200+
clearInterval(intervalId)
201+
source?.disconnect()
202+
audioContext?.close()
203+
}
204+
196205
return {
197-
onDestroy: () => {
198-
clearInterval(intervalId)
199-
source?.disconnect()
200-
audioContext?.close()
201-
},
206+
onDestroy: cleanup,
202207
onEnd: () => {
203208
this.isWaveformPaused = true
204-
clearInterval(intervalId)
205209
this.stopMic()
206210
},
207211
}
@@ -218,16 +222,23 @@ class RecordPlugin extends BasePlugin<RecordPluginEvents, RecordPluginOptions> {
218222
throw new Error('Error accessing the microphone: ' + (err as Error).message)
219223
}
220224

221-
const { onDestroy, onEnd } = this.renderMicStream(stream)
222-
this.subscriptions.push(this.once('destroy', onDestroy))
223-
this.subscriptions.push(this.once('record-end', onEnd))
225+
const micStream = this.renderMicStream(stream)
226+
this.micStream = micStream
227+
this.unsubscribeDestroy = this.once('destroy', micStream.onDestroy)
228+
this.unsubscribeRecordEnd = this.once('record-end', micStream.onEnd)
224229
this.stream = stream
225230

226231
return stream
227232
}
228233

229234
/** Stop monitoring incoming audio */
230235
public stopMic() {
236+
this.micStream?.onDestroy()
237+
this.unsubscribeDestroy?.()
238+
this.unsubscribeRecordEnd?.()
239+
this.micStream = null
240+
this.unsubscribeDestroy = undefined
241+
this.unsubscribeRecordEnd = undefined
231242
if (!this.stream) return
232243
this.stream.getTracks().forEach((track) => track.stop())
233244
this.stream = null

0 commit comments

Comments
 (0)