Created
July 29, 2021 21:04
-
-
Save lmcarreiro/fa925c151972b01a8ee42ed87d848b2f to your computer and use it in GitHub Desktop.
STT+VAD article - useAudioActive.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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