> ## Documentation Index
> Fetch the complete documentation index at: https://ai-kb.automationanywhere.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Voice SDK

> वॉयस-सक्षम अनुप्रयोग और AI एजेंट बनाएँ।

VoiceSDK स्वचालित चैट सिस्टम एकीकरण और वॉयस-सक्षम अनुप्रयोग बनाने के लिए React hooks के साथ उन्नत वॉयस वार्तालाप क्षमताएँ प्रदान करता है। AI एजेंट्स के साथ प्राकृतिक वॉयस इंटरैक्शन बनाएँ, ऑडियो विज़ुअलाइज़ेशन, ट्रांसक्रिप्शन और वार्तालाप प्रबंधन के साथ। इस लेख में एक त्वरित आरंभ उदाहरण है जो न केवल आपको जल्दी शुरू करेगा, बल्कि यह समझने में भी मदद करेगा कि यह कैसे काम करता है। लेख का शेष भाग विभिन्न विधियों, उनके उपयोग और सर्वोत्तम प्रथाओं का विवरण देता है।

## इंस्टॉलेशन

```bash theme={null}
npm install @odin-ai-staging/sdk @elevenlabs/react
```

## त्वरित आरंभ

### बुनियादी वॉयस वार्तालाप

इस उदाहरण में, आप TypeScript और React अनुप्रयोगों दोनों में VoiceSDK का उपयोग करके वास्तविक समय वॉयस वार्तालाप लागू करना सीखेंगे।

```typescript theme={null}
import { VoiceSDK } from '@odin-ai-staging/sdk';

// SDK को आरंभ करें
const voiceSDK = new VoiceSDK({
  baseUrl: 'https://your-api-endpoint.com/',
  projectId: 'your-project-id',
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret',
  agentId: 'your-agent-id'
});

// वॉयस वार्तालाप प्रारंभ करें
async function startVoiceChat() {
  const sessionId = await voiceSDK.startVoiceConversation({
    saveToChat: true,
    callbacks: {
      onConnect: () => console.log('वॉयस कनेक्टेड'),
      onMessage: (message) => console.log('वॉयस संदेश:', message),
      onDisconnect: () => console.log('वॉयस डिस्कनेक्टेड'),
      onTranscription: (text, isFinal) => {
        if (isFinal) console.log('उपयोगकर्ता ने कहा:', text);
      }
    }
  });
  
  console.log('वॉयस सत्र प्रारंभ:', sessionId);
}
```

### React Hook उपयोग

```tsx theme={null}
import { useVoiceConversation } from '@odin-ai-staging/sdk';

function VoiceChat() {
  const {
    status,
    startSession,
    endSession,
    setVolume,
    getInputByteFrequencyData,
    conversationState
  } = useVoiceConversation({
    sdkConfig: {
      baseUrl: 'https://your-api-endpoint.com/',
      projectId: 'your-project-id',
      agentId: 'your-agent-id'
    },
    callbacks: {
      onConnect: () => console.log('कनेक्टेड!'),
      onMessage: (message) => console.log('संदेश:', message)
    }
  });

  return (
    <div>
      <button 
        onClick={() => startSession()}
        disabled={status === 'connected'}
      >
        वॉयस चैट प्रारंभ करें
      </button>
      
      <button 
        onClick={() => endSession()}
        disabled={status !== 'connected'}
      >
        चैट समाप्त करें
      </button>
      
      <div>स्थिति: {status}</div>
      <div>वॉल्यूम: {conversationState.volume}</div>
    </div>
  );
}
```

## कॉन्फ़िगरेशन

### VoiceSDKConfig इंटरफ़ेस

```typescript theme={null}
interface VoiceSDKConfig extends BaseClientConfig {
  agentId?: string;            // डिफ़ॉल्ट एजेंट ID
  defaultVoiceSettings?: VoiceSettings;  // डिफ़ॉल्ट वॉयस कॉन्फ़िगरेशन
}
```

### VoiceSettings

```typescript theme={null}
interface VoiceSettings {
  stability?: number;          // वॉयस स्थिरता (0.0 से 1.0)
  similarityBoost?: number;    // वॉयस समानता बूस्ट (0.0 से 1.0)
  style?: number;             // वॉयस शैली (0.0 से 1.0)
  useSpeakerBoost?: boolean;  // स्पीकर बूस्ट सक्षम करें
}
```

**उदाहरण कॉन्फ़िगरेशन:**

```typescript theme={null}
const voiceSDK = new VoiceSDK({
  baseUrl: 'https://api.example.com/',
  projectId: 'proj_123',
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret',
  agentId: 'agent_456',
  defaultVoiceSettings: {
    stability: 0.8,
    similarityBoost: 0.7,
    style: 0.3,
    useSpeakerBoost: true
  }
});
```

## मूल सुविधाएँ

### वॉयस वार्तालाप सत्र

```typescript theme={null}
interface VoiceConversationSession {
  id: string;                    // सत्र पहचानकर्ता
  chatId?: string;               // संबद्ध चैट ID
  startTime: number;             // सत्र प्रारंभ टाइमस्टैम्प
  endTime?: number;              // सत्र समाप्ति टाइमस्टैम्प
  messages: VoiceMessage[];      // सत्र में वॉयस संदेश
  metadata?: {
    agentId?: string;
    voiceSettings?: VoiceSettings;
    totalDuration?: number;
    userInfo?: { name: string; id: string };
  };
}
```

### वॉयस संदेश

```typescript theme={null}
interface VoiceMessage {
  id: string;                    // संदेश ID
  type: 'user_speech' | 'ai_speech' | 'system';
  text: string;                  // ट्रांसक्रिब्ड/उत्पन्न टेक्स्ट
  audioUrl?: string;             // ऑडियो फ़ाइल URL
  timestamp: number;             // संदेश टाइमस्टैम्प
  duration?: number;             // ऑडियो अवधि सेकंड में
  voiceSettings?: VoiceSettings; // उपयोग की गई वॉयस सेटिंग्स
  saved?: boolean;               // डेटाबेस में सहेजा गया
}
```

## सत्र प्रबंधन

### `startVoiceConversation(options?)`

एक नई वॉयस वार्तालाप सत्र प्रारंभ करें।

```typescript theme={null}
async startVoiceConversation(
  options?: StartVoiceConversationOptions
): Promise<string>
```

**StartVoiceConversationOptions:**

```typescript theme={null}
interface StartVoiceConversationOptions {
  callbacks?: VoiceConversationCallbacks;
  saveToChat?: boolean;          // चैट इतिहास में स्वतः सहेजें
  existingChatId?: string;       // मौजूदा चैट जारी रखें
  agentId?: string;             // डिफ़ॉल्ट एजेंट ओवरराइड करें
  voiceSettings?: VoiceSettings; // कस्टम वॉयस सेटिंग्स
  userInfo?: { name: string; id: string };
}
```

**उदाहरण:**

```typescript theme={null}
const sessionId = await voiceSDK.startVoiceConversation({
  saveToChat: true,
  existingChatId: 'chat_123',
  voiceSettings: {
    stability: 0.9,
    similarityBoost: 0.8
  },
  userInfo: {
    name: 'जॉन डो',
    id: 'user_456'
  },
  callbacks: {
    onConnect: () => console.log('वॉयस वार्तालाप प्रारंभ'),
    onMessage: (message) => handleVoiceMessage(message),
    onTranscription: (text, isFinal) => {
      if (isFinal) displayTranscription(text);
    },
    onConversationSaved: (chatId, messageId) => {
      console.log(`वार्तालाप चैट ${chatId} में सहेजा गया`);
    }
  }
});
```

### `endVoiceSession(sessionId, reason?)`

एक वॉयस वार्तालाप सत्र समाप्त करें।

```typescript theme={null}
async endVoiceSession(sessionId: string, reason?: string): Promise<void>
```

**उदाहरण:**

```typescript theme={null}
await voiceSDK.endVoiceSession(sessionId, 'उपयोगकर्ता ने वार्तालाप समाप्त किया');
```

### `getVoiceState(sessionId)`

वर्तमान वॉयस वार्तालाप स्थिति प्राप्त करें।

```typescript theme={null}
getVoiceState(sessionId: string): VoiceConversationState | null
```

**उदाहरण:**

```typescript theme={null}
const state = voiceSDK.getVoiceState(sessionId);
if (state) {
  console.log('कनेक्शन स्थिति:', state.connectionStatus);
  console.log('बोल रहे हैं:', state.isSpeaking);
  console.log('वॉल्यूम:', state.volume);
}
```

## React एकीकरण

### useVoiceConversation Hook

```typescript theme={null}
function useVoiceConversation(options: VoiceHookOptions): {
  status: VoiceStatus;
  isSpeaking: boolean;
  startSession: (config?: VoiceSessionConfig) => Promise<string>;
  endSession: () => Promise<void>;
  setVolume: (options: { volume: number }) => void;
  conversationState: VoiceConversationState;
  currentSessionId: string | null;
  getInputByteFrequencyData: () => Uint8Array | null;
  getOutputByteFrequencyData: () => Uint8Array | null;
}
```

**पूर्ण React उदाहरण:**

```tsx theme={null}
import React, { useState } from 'react';
import { useVoiceConversation } from '@odin-ai-staging/sdk';

function VoiceConversationComponent() {
  const [messages, setMessages] = useState<string[]>([]);
  const [isRecording, setIsRecording] = useState(false);

  const {
    status,
    isSpeaking,
    startSession,
    endSession,
    setVolume,
    conversationState,
    currentSessionId,
    getInputByteFrequencyData
  } = useVoiceConversation({
    sdkConfig: {
      baseUrl: process.env.REACT_APP_API_BASE_URL,
      projectId: process.env.REACT_APP_PROJECT_ID,
      agentId: process.env.REACT_APP_AGENT_ID
    },
    callbacks: {
      onConnect: () => {
        console.log('वॉयस चैट से जुड़े');
        setIsRecording(true);
      },
      onDisconnect: () => {
        console.log('वॉयस चैट से डिस्कनेक्टेड');
        setIsRecording(false);
      },
      onTranscription: (text, isFinal) => {
        if (isFinal) {
          setMessages(prev => [...prev, `आप: ${text}`]);
        }
      },
      onMessage: (message) => {
        if (message.type === 'ai_speech') {
          setMessages(prev => [...prev, `AI: ${message.text}`]);
        }
      },
      onError: (error) => {
        console.error('वॉयस त्रुटि:', error);
        setIsRecording(false);
      }
    }
  });

  const handleStartConversation = async () => {
    try {
      await startSession({
        saveToChat: true,
        voiceSettings: {
          stability: 0.8,
          similarityBoost: 0.7
        }
      });
    } catch (error) {
      console.error('वार्तालाप प्रारंभ करने में विफल:', error);
    }
  };

  const handleEndConversation = async () => {
    try {
      await endSession();
    } catch (error) {
      console.error('वार्तालाप समाप्त करने में विफल:', error);
    }
  };

  const handleVolumeChange = (volume: number) => {
    setVolume({ volume });
  };

  return (
    <div className="voice-conversation">
      <div className="controls">
        <button 
          onClick={handleStartConversation}
          disabled={status === 'connected'}
        >
          वॉयस चैट प्रारंभ करें
        </button>
        
        <button 
          onClick={handleEndConversation}
          disabled={status !== 'connected'}
        >
          वॉयस चैट समाप्त करें
        </button>
      </div>

      <div className="status">
        <div>स्थिति: {status}</div>
        <div>बोल रहे हैं: {isSpeaking ? 'हाँ' : 'नहीं'}</div>
        <div>रिकॉर्डिंग: {isRecording ? 'हाँ' : 'नहीं'}</div>
        <div>वॉल्यूम: {conversationState.volume}</div>
      </div>

      <div className="volume-control">
        <label>वॉल्यूम:</label>
        <input
          type="range"
          min="0"
          max="100"
          value={conversationState.volume}
          onChange={(e) => handleVolumeChange(parseInt(e.target.value))}
        />
      </div>

      <div className="messages">
        {messages.map((message, index) => (
          <div key={index} className="message">
            {message}
          </div>
        ))}
      </div>

      {currentSessionId && (
        <AudioVisualizer 
          getInputData={getInputByteFrequencyData}
          isActive={status === 'connected'}
        />
      )}
    </div>
  );
}
```

## वॉयस नियंत्रण

### वॉल्यूम नियंत्रण

```typescript theme={null}
// वॉल्यूम सेट करें (0-100)
await voiceSDK.setVolume(sessionId, 75);
```

### माइक्रोफ़ोन नियंत्रण

```typescript theme={null}
// माइक्रोफ़ोन म्यूट/अनम्यूट
await voiceSDK.setMicrophoneMuted(sessionId, true);  // म्यूट
await voiceSDK.setMicrophoneMuted(sessionId, false); // अनम्यूट
```

### वॉयस सेटिंग्स अपडेट

```typescript theme={null}
// वार्तालाप के दौरान वॉयस सेटिंग्स अपडेट करें
await voiceSDK.updateVoiceSettings(sessionId, {
  stability: 0.9,
  similarityBoost: 0.8,
  style: 0.4
});
```

## ऑडियो विज़ुअलाइज़ेशन

### वास्तविक समय ऑडियो डेटा

```typescript theme={null}
// विज़ुअलाइज़ेशन के लिए ऑडियो फ़्रीक्वेंसी डेटा प्राप्त करें
const audioData = voiceSDK.getAudioFrequencyData(sessionId);

if (audioData) {
  const inputData = audioData.input;   // उपयोगकर्ता का ऑडियो इनपुट
  const outputData = audioData.output; // AI का ऑडियो आउटपुट
  
  renderAudioVisualization(inputData, outputData);
}
```

## चैट एकीकरण

### स्वचालित चैट सेविंग

```typescript theme={null}
const sessionId = await voiceSDK.startVoiceConversation({
  saveToChat: true,
  existingChatId: 'chat_123',
  callbacks: {
    onConversationSaved: (chatId, messageId) => {
      console.log(`वॉयस वार्तालाप चैट ${chatId} में सहेजा गया`);
      refreshChatHistory(chatId);
    }
  }
});
```

### मैनुअल चैट एकीकरण

```typescript theme={null}
// वॉयस सत्र से वार्तालाप इतिहास प्राप्त करें
const messages = voiceSDK.getConversationHistory(sessionId);

// मैनुअल रूप से चैट में सहेजें
for (const message of messages) {
  if (message.type === 'user_speech') {
    await chatSDK.sendMessage(message.text, {
      chatId: 'chat_123',
      metadata: {
        voiceMessage: true,
        audioUrl: message.audioUrl,
        sessionId: sessionId
      }
    });
  }
}
```

### संदर्भ अपडेट

```typescript theme={null}
// चैट इतिहास से संदर्भ भेजें
await voiceSDK.sendContextualUpdate(
  sessionId,
  'उपयोगकर्ता ने पहले मूल्य निर्धारण के बारे में पूछा था। वर्तमान वार्तालाप सुविधाओं के बारे में है।'
);
```

## त्रुटि हैंडलिंग

```typescript theme={null}
try {
  const sessionId = await voiceSDK.startVoiceConversation({
    callbacks: {
      onError: (error) => {
        console.error('वॉयस वार्तालाप त्रुटि:', error);
        
        if (error.message.includes('microphone')) {
          showMicrophonePermissionDialog();
        } else if (error.message.includes('network')) {
          showNetworkErrorMessage();
        }
      },
      onDisconnect: (details) => {
        console.log('डिस्कनेक्टेड:', details?.reason);
        
        if (details?.reason === 'user_ended') {
          showConversationSummary();
        } else if (details?.reason === 'error') {
          showReconnectOption();
        }
      }
    }
  });
} catch (error) {
  console.error('वॉयस वार्तालाप प्रारंभ करने में विफल:', error);
  
  if (error.message.includes('agent')) {
    showAgentConfigError();
  }
}
```

## सर्वोत्तम प्रथाएँ

### त्रुटि हैंडलिंग और फ़ॉलबैक

```typescript theme={null}
const voiceSupport = {
  async startWithFallback() {
    try {
      return await this.voiceSDK.startVoiceConversation(options);
    } catch (error) {
      console.warn('वॉयस विफल, टेक्स्ट चैट पर फ़ॉलबैक:', error);
      return await this.chatSDK.createChat('सहायता चैट (टेक्स्ट)');
    }
  }
};
```

### संसाधन प्रबंधन

```typescript theme={null}
class VoiceManager {
  private activeSessions = new Set<string>();

  async startSession(options: any) {
    const sessionId = await this.voiceSDK.startVoiceConversation(options);
    this.activeSessions.add(sessionId);
    return sessionId;
  }

  async cleanup() {
    for (const sessionId of this.activeSessions) {
      try {
        await this.voiceSDK.endVoiceSession(sessionId);
      } catch (error) {
        console.warn('सत्र समाप्त करने में विफल:', sessionId, error);
      }
    }
    this.activeSessions.clear();
  }
}
```

### प्रदर्शन अनुकूलन

```typescript theme={null}
const AudioVisualizer = React.memo(({ getInputData, isActive }) => {
  const throttledAnimate = useCallback(
    throttle(() => {
      // एनिमेशन लॉजिक
    }, 16),
    []
  );
  // ... कंपोनेंट लॉजिक
});
```

### सुलभता

```typescript theme={null}
function VoiceAccessibleChat() {
  const [transcript, setTranscript] = useState('');
  
  const { startSession } = useVoiceConversation({
    callbacks: {
      onTranscription: (text, isFinal) => {
        setTranscript(text);
        if (isFinal) {
          announceToScreenReader(`आपने कहा: ${text}`);
        }
      }
    }
  });

  return (
    <div>
      <button 
        aria-label="वॉयस वार्तालाप प्रारंभ करें"
        onClick={startSession}
      >
        🎤 वॉयस चैट प्रारंभ करें
      </button>
      
      <div 
        aria-live="polite"
        aria-label="वॉयस ट्रांसक्रिप्ट"
      >
        {transcript}
      </div>
    </div>
  );
}
```
