Skip to content

Instantly share code, notes, and snippets.

@lmcarreiro
Created July 29, 2021 21:04
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 lmcarreiro/fa925c151972b01a8ee42ed87d848b2f to your computer and use it in GitHub Desktop.
Save lmcarreiro/fa925c151972b01a8ee42ed87d848b2f to your computer and use it in GitHub Desktop.
STT+VAD article - useAudioActive.ts
import { useEffect, useState } from "react";
import hark from "hark";
export function useAudioActive(stream: MediaStream | undefined) {
const [speakerActive, setSpeakerActive] = React.useState(false);
React.useEffect(() => {
if (!stream) {
setSpeakerActive(false);
return;
}
const speech = hark(stream, { play: false });
speech.on("speaking", () => {
console.log("hark speaking");
setSpeakerActive(true);
});
speech.on("stopped_speaking", () => {
console.log("hark stopped_speaking");
setSpeakerActive(false);
});
return () => {
// `hark` typing definition doesn't have the `.off()` function to unbind the event handle
// but as it uses `wildemitter` npm package, this function does exist.
// @ts-ignore
speech.off("speaking");
// @ts-ignore
speech.off("stopped_speaking");
speech.stop();
};
}, [stream]);
return speakerActive;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment