Skip to content

Commit 08b2f1d

Browse files
committed
Enhance voice activity detection by adding configurable thresholds for detecting voice start and stop times.
1 parent ff8a4d6 commit 08b2f1d

1 file changed

Lines changed: 6 additions & 3 deletions

File tree

src/peer-connection.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -557,18 +557,21 @@ function handleTransceiverForInsertableStreams(id: number, transceiver: RTCRtpTr
557557
/**
558558
* It detects voice activity on an audio track and calls the callback with the start and stop times.
559559
* @param track - The track to detect voice activity on.
560+
* @param lowThreshold - The low threshold to detect voice stop.
561+
* @param highThreshold - The high threshold to detect voice start.
560562
* @param callback - The callback to call with the start and stop times.
561563
* @returns The cleanup function to stop the detection.
562564
*/
563565
export function detectVoiceActivity(
564566
track: MediaStreamTrack,
567+
lowThreshold = 0.001,
568+
highThreshold = 0.1,
565569
callback?: (event: 'start' | 'stop', startTime: number, stopTime: number) => void,
566570
) {
567571
if (track.kind !== 'audio' || track.readyState !== 'live') return
568572
log(`detectVoiceActivity track id: ${track.id}`)
569573
const audioCtx = new AudioContext({
570574
sampleRate: 48000,
571-
latencyHint: 'interactive',
572575
})
573576
const source = audioCtx.createMediaStreamSource(new MediaStream([track]))
574577
const analyser = audioCtx.createAnalyser()
@@ -590,7 +593,7 @@ export function detectVoiceActivity(
590593
if (audioCtx.state === 'running') {
591594
analyser.getFloatTimeDomainData(dataArray)
592595
const max = Math.max(...dataArray)
593-
if (max > 0.1 && !startTime) {
596+
if (max > highThreshold && !startTime) {
594597
startTime = Date.now()
595598
if (stopTime) {
596599
log(
@@ -599,7 +602,7 @@ export function detectVoiceActivity(
599602
callback?.('start', startTime, stopTime)
600603
}
601604
stopTime = 0
602-
} else if (max <= 0.001 && startTime && !stopTime) {
605+
} else if (max <= lowThreshold && startTime && !stopTime) {
603606
stopTime = Date.now()
604607
log(
605608
`voice stopped track id: ${track.id} max: ${max} at ${stopTime} voice duration: ${stopTime - startTime}ms`,

0 commit comments

Comments
 (0)