@airsurfer09/web-handsfree
Version:
A React package for integrating Convai's AI-powered voice assistants with LiveKit for real-time audio/video conversations
65 lines • 2.01 kB
JavaScript
import { useCallback } from "react";
import { logger } from "../utils/logger";
/**
* Hook for toggling TTS (Text-to-Speech) generation in Convai.
*
* Sends a tts-toggle message to control whether the bot generates audio.
* This is more efficient than muting audio after generation, as it prevents
* audio generation at the source.
*
* @param {Room} room - LiveKit room instance
* @returns {Object} Object containing toggleTts function
*
* @example
* ```tsx
* function AudioControlComponent() {
* const { toggleTts } = useTtsToggle(room);
*
* const handleMute = () => {
* toggleTts(false); // Disable TTS generation
* };
*
* const handleUnmute = () => {
* toggleTts(true); // Enable TTS generation
* };
*
* return (
* <div>
* <button onClick={handleMute}>Mute TTS</button>
* <button onClick={handleUnmute}>Unmute TTS</button>
* </div>
* );
* }
* ```
*/
export const useTtsToggle = (room) => {
const toggleTts = useCallback((enabled) => {
// Check if room is connected and localParticipant exists
if (!room || room.state === 'disconnected' || !room.localParticipant) {
logger.warn("Cannot toggle TTS: room is disconnected or localParticipant is unavailable");
return;
}
try {
const message = {
type: "tts-toggle",
data: {
"enabled": enabled
}
};
const encodedData = new TextEncoder().encode(JSON.stringify(message));
room.localParticipant.publishData(encodedData, {
reliable: true,
});
logger.log(`🔊 TTS ${enabled ? 'enabled' : 'disabled'}`);
}
catch (error) {
logger.error("Failed to toggle TTS:", error);
// Re-throw to allow caller to handle
throw error;
}
}, [room]);
return {
toggleTts,
};
};
//# sourceMappingURL=useTtsToggle.js.map