Skip to Content
HooksuseVoiceSession

useVoiceSession

The primary hook for controlling voice sessions. Provides methods to connect and disconnect, plus access to the current session ID and errors.

Import

import { useVoiceSession } from '@vocobase/voice-client-sdk'

Requirements

This hook must be used within a VoiceSessionProvider:

import { VoiceSessionProvider } from '@vocobase/voice-client-sdk' function App() { return ( <VoiceSessionProvider apiKey="rg_live_xxx" agentName="my-agent"> <YourComponent /> </VoiceSessionProvider> ) }

Return Value

const { connect, // () => Promise<void> disconnect, // () => Promise<void> sessionId, // string | null error // VoiceAgentError | null } = useVoiceSession()

connect

Initiates a voice session. This function:

  1. Requests microphone permission
  2. Calls the Vocobase API to create a session
  3. Establishes the voice connection

disconnect

Ends the current voice session gracefully.

sessionId

The unique identifier for the current session. null when not connected.

error

The most recent error, or null if no error.

Example

function VoiceControls() { const { connect, disconnect, sessionId, error } = useVoiceSession() const { isConnected, isConnecting } = useConnectionState() return ( <div> {error && <div className="error">{error.message}</div>} {!isConnected ? ( <button onClick={connect} disabled={isConnecting}> {isConnecting ? 'Connecting...' : 'Start Call'} </button> ) : ( <> <p>Session: {sessionId}</p> <button onClick={disconnect}>End Call</button> </> )} </div> ) }

Error Handling

function VoiceControls() { const { connect, error } = useVoiceSession() if (error) { switch (error.code) { case 'MIC_PERMISSION_DENIED': return <MicrophonePermissionPrompt /> case 'INSUFFICIENT_CREDITS': return <UpgradePrompt /> case 'CONCURRENCY_LIMIT': return <p>Too many active calls. Please try again later.</p> default: return <p>Error: {error.message}</p> } } return <button onClick={connect}>Start</button> }
Last updated on