Skip to content

Instantly share code, notes, and snippets.

@enricop89
Created July 15, 2022 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enricop89/41b96933377ad21055563a1d715b0b39 to your computer and use it in GitHub Desktop.
Save enricop89/41b96933377ad21055563a1d715b0b39 to your computer and use it in GitHub Desktop.
Use audioLevelUpdated
import _ from "lodash";
const speakingThreshold = 1000;
const notSpeakingThreshold = 2000;
const audioStream = {
isTalking: false,
timestamp: 0,
};
const onAudioLevel = function(event, elementId) {
const now = new Date().getTime();
if (event && event.audioLevel > 0.2) {
// it could be speaking
if (!audioStream.isTalking) {
audioStream.isTalking = true;
audioStream.timestamp = new Date().getTime();
} else if (
audioStream.isTalking &&
now - audioStream.timestamp > speakingThreshold
) {
audioStream.isTalking = true;
audioStream.timestamp = new Date().getTime();
// this means that it's speaking for more than X seconds
// Call your UI function to update the active speaker
updateActiveSpeakerEl(elementId, "add");
}
} else if (
audioStream.isTalking &&
now - audioStream.timestamp > notSpeakingThreshold
) {
// low audio detected for X seconds
audioStream.isTalking = false;
updateActiveSpeakerEl(elementId, "remove");
}
};
}
subscriber.on("audioLevelUpdated", _.throttle((event) => onAudioLevel(event, subscriber.id), 50));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment