> This is a page from the ElevenLabs documentation. For a complete page index, fetch https://elevenlabs.io/docs/llms.txt. For the full documentation in a single file, fetch https://elevenlabs.io/docs/llms-full.txt.

# React SDK

> **Info**
>
> Scribe और इसकी क्षमताओं के बारे में जानने के लिए [स्पीच टू टेक्स्ट ओवरव्यू](/docs/hi/capabilities/speech-to-text) देखें। चरण-दर-चरण इस्तेमाल गाइड्स के लिए [क्लाइंट-साइड स्ट्रीमिंग](/docs/hi/eleven-api/guides/how-to/speech-to-text/realtime/client-side-streaming) देखें।

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

```shell
npm install @elevenlabs/react
# or
yarn add @elevenlabs/react
# or
pnpm install @elevenlabs/react
```

> **Tip**
>
> अपने AI कोडिंग असिस्टेंट से ऑडियो ट्रांसक्राइब करने के लिए [ElevenLabs स्पीच-टू-टेक्स्ट स्किल](https://github.com/elevenlabs/skills/tree/main/speech-to-text) इस्तेमाल करें:
>
> ```bash
> npx skills add elevenlabs/skills --skill speech-to-text
> ```

> **Note**
>
> `@elevenlabs/react`, `@elevenlabs/client` से सब कुछ फिर से एक्सपोर्ट करता है, इसलिए आपको
> दोनों पैकेज इंस्टॉल करने की ज़रूरत नहीं है।

## इस्तेमाल

यहां Scribe से कनेक्ट होने और रीयल-टाइम ट्रांसक्रिप्शन दिखाने का एक न्यूनतम काम करने वाला उदाहरण है:

```tsx
import { useScribe } from "@elevenlabs/react";
import { useEffect } from "react";

function MyComponent() {
  const scribe = useScribe({
    modelId: "scribe_v2_realtime",
    onPartialTranscript: (data) => {
      console.log("Partial:", data.text);
    },
    onCommittedTranscript: (data) => {
      console.log("Committed:", data.text);
    },
  });

  // Start recording
  const handleStart = async () => {
    try {
      const token = await fetchTokenFromServer();
      await scribe.connect({
        token,
        microphone: {
          echoCancellation: true,
          noiseSuppression: true,
        },
      });
    } catch (err) {
      console.error("Failed to start recording:", err);
    }
  };

  // Stop recording
  const handleDisconnect = () => {
    scribe.disconnect();
  };

  // Disconnect on unmount
  useEffect(() => {
    return () => {
      if (scribe.isConnected) {
        scribe.disconnect();
      }
    };
  }, [scribe]);

  return (
    <div>
      <button onClick={handleStart} disabled={scribe.isConnected}>
        Start Recording
      </button>
      <button onClick={handleDisconnect} disabled={!scribe.isConnected}>
        Stop
      </button>

      {scribe.partialTranscript && <p>Live: {scribe.partialTranscript}</p>}

      <div>
        {scribe.committedTranscripts.map((t) => (
          <p key={t.id}>{t.text}</p>
        ))}
      </div>
    </div>
  );
}
```

## टोकन पाना

Scribe को ऑथेंटिकेशन के लिए एक बार इस्तेमाल होने वाला टोकन चाहिए। अपने सर्वर पर एक API एंडपॉइंट बनाएं:

```js
// Node.js server
app.get("/scribe-token", yourAuthMiddleware, async (req, res) => {
  const response = await fetch("https://api.elevenlabs.io/v1/single-use-token/realtime_scribe", {
    method: "POST",
    headers: {
      "xi-api-key": process.env.ELEVENLABS_API_KEY,
    },
  });

  const data = await response.json();
  res.json({ token: data.token });
});
```

> **Warning**
>
> आपकी ElevenLabs API कुंजी संवेदनशील है। इसे कभी क्लाइंट के सामने न दिखाएं। टोकन हमेशा
> सर्वर पर जनरेट करें।

```tsx
// Client
const fetchToken = async () => {
  const response = await fetch("/scribe-token");
  const { token } = await response.json();
  return token;
};
```

## हुक विकल्प

हुक को डिफ़ॉल्ट विकल्पों और कॉलबैक के साथ कॉन्फ़िगर करें:

```tsx
const scribe = useScribe({
  // Connection options (can be overridden in connect())
  token: "optional-default-token",
  modelId: "scribe_v2_realtime",
  baseUri: "wss://api.elevenlabs.io",

  // VAD options
  commitStrategy: CommitStrategy.VAD,
  vadSilenceThresholdSecs: 0.5,
  vadThreshold: 0.5,
  minSpeechDurationMs: 100,
  minSilenceDurationMs: 500,
  languageCode: "en",

  // Microphone options (for automatic mode)
  microphone: {
    deviceId: "optional-device-id",
    echoCancellation: true,
    noiseSuppression: true,
    autoGainControl: true,
  },

  // Manual audio options (for file transcription)
  audioFormat: AudioFormat.PCM_16000,
  sampleRate: 16000,

  // Auto-connect on mount
  autoConnect: false,

  // Event callbacks
  onSessionStarted: () => console.log("Session started"),
  onPartialTranscript: (data) => console.log("Partial:", data.text),
  onCommittedTranscript: (data) => console.log("Committed:", data.text),
  onCommittedTranscriptWithTimestamps: (data) => console.log("With timestamps:", data),
  onError: (error) => console.error("Error:", error),
  onAuthError: (data) => console.error("Auth error:", data.error),
  onQuotaExceededError: (data) => console.error("Quota exceeded:", data.error),
  onConnect: () => console.log("Connected"),
  onDisconnect: () => console.log("Disconnected"),
});
```

### कनेक्शन विकल्प

| प्रॉपर्टी   | टाइप     | विवरण                                                           |
| ----------- | -------- | --------------------------------------------------------------- |
| **token**   | `string` | WebSocket ऑथेंटिकेशन के लिए एक बार इस्तेमाल होने वाला टोकन।     |
| **modelId** | `string` | मॉडल ID (जैसे, `"scribe_v2_realtime"`)।                         |
| **baseUri** | `string` | कस्टम WebSocket बेस URI। डिफ़ॉल्ट `wss://api.elevenlabs.io` है। |

### VAD विकल्प

`VAD` कमिट स्ट्रैटेजी इस्तेमाल करते समय ये विकल्प नियंत्रित करते हैं कि ट्रांसक्रिप्ट अपने-आप कब कमिट हों।

| प्रॉपर्टी                   | टाइप             | डिफ़ॉल्ट   | विवरण                                                     |
| --------------------------- | ---------------- | ---------- | --------------------------------------------------------- |
| **commitStrategy**          | `CommitStrategy` | `"manual"` | `"manual"` या `"vad"`।                                    |
| **vadSilenceThresholdSecs** | `number`         | `1.5`      | VAD के कमिट करने से पहले साइलेंस के सेकंड (0.3-3.0)।      |
| **vadThreshold**            | `number`         | `0.4`      | VAD संवेदनशीलता (0.1-0.9, कम मान अधिक संवेदनशील होता है)। |
| **minSpeechDurationMs**     | `number`         | `100`      | न्यूनतम बोलने की अवधि, ms में (50-2000)।                  |
| **minSilenceDurationMs**    | `number`         | `100`      | न्यूनतम साइलेंस अवधि, ms में (50-2000)।                   |

### ऑडियो विकल्प

| प्रॉपर्टी        | टाइप          | विवरण                                                                         |
| ---------------- | ------------- | ----------------------------------------------------------------------------- |
| **languageCode** | `string`      | ISO-639-1 या ISO-639-3 भाषा कोड। ऑटो-डिटेक्शन के लिए खाली छोड़ें।             |
| **microphone**   | `object`      | माइक्रोफ़ोन मोड के लिए माइक्रोफ़ोन सेटिंग्स। नीचे देखें।                      |
| **audioFormat**  | `AudioFormat` | मैन्युअल मोड के लिए ऑडियो एन्कोडिंग फ़ॉर्मैट (जैसे, `AudioFormat.PCM_16000`)। |
| **sampleRate**   | `number`      | मैन्युअल मोड के लिए सैंपल रेट। `audioFormat` से मेल खाना चाहिए।               |

`microphone` ऑब्जेक्ट ये स्वीकार करता है:

| प्रॉपर्टी            | टाइप      | विवरण                              |
| -------------------- | --------- | ---------------------------------- |
| **deviceId**         | `string`  | किसी खास माइक्रोफ़ोन का डिवाइस ID। |
| **echoCancellation** | `boolean` | इको कैंसलेशन चालू करें।            |
| **noiseSuppression** | `boolean` | नॉइज़ सप्रेशन चालू करें।           |
| **autoGainControl**  | `boolean` | ऑटोमैटिक गेन कंट्रोल चालू करें।    |

### व्यवहार विकल्प

| प्रॉपर्टी             | टाइप      | डिफ़ॉल्ट | विवरण                                                                                                |
| --------------------- | --------- | -------- | ---------------------------------------------------------------------------------------------------- |
| **autoConnect**       | `boolean` | `false`  | कंपोनेंट माउंट होने पर अपने-आप कनेक्ट करें।                                                          |
| **includeTimestamps** | `boolean` | `false`  | शब्द-स्तरीय टाइमस्टैंप पाएं। `onCommittedTranscriptWithTimestamps` दिए जाने पर अपने-आप चालू होता है। |

### कॉलबैक

सभी इवेंट कॉलबैक वैकल्पिक हैं और हुक विकल्पों के रूप में दिए जा सकते हैं:

* **onConnect** - WebSocket कनेक्शन स्थापित होने पर कॉल किया जाने वाला हैंडलर।
* **onDisconnect** - WebSocket कनेक्शन बंद होने पर कॉल किया जाने वाला हैंडलर।
* **onSessionStarted** - Scribe सेशन शुरू होने पर कॉल किया जाने वाला हैंडलर।
* **onPartialTranscript** - अस्थायी ट्रांसक्रिप्शन नतीजों के साथ कॉल किया जाने वाला हैंडलर। `{ text: string }` प्राप्त करता है।
* **onCommittedTranscript** - फ़ाइनल ट्रांसक्रिप्शन नतीजों के साथ कॉल किया जाने वाला हैंडलर। `{ text: string }` प्राप्त करता है।
* **onCommittedTranscriptWithTimestamps** - शब्द-स्तरीय टाइमिंग समेत फ़ाइनल ट्रांसक्रिप्शन नतीजों के साथ कॉल किया जाने वाला हैंडलर। `{ text: string; words?: { start: number; end: number }[] }` प्राप्त करता है।
* **onError** - सभी त्रुटियों के लिए सामान्य एरर हैंडलर। `Error | Event` प्राप्त करता है।
* **onAuthError** - ऑथेंटिकेशन त्रुटियों पर कॉल किया जाने वाला हैंडलर। `{ error: string }` प्राप्त करता है।

#### एरर कॉलबैक

सामान्य `onError` कॉलबैक सभी त्रुटियों के लिए ट्रिगर होता है। विस्तृत हैंडलिंग के लिए खास एरर कॉलबैक भी उपलब्ध हैं। सभी खास एरर कॉलबैक `{ error: string }` प्राप्त करते हैं।

| कॉलबैक                               | विवरण                                                    |
| ------------------------------------ | -------------------------------------------------------- |
| **onError**                          | सभी त्रुटियों के लिए सामान्य एरर हैंडलर।                 |
| **onAuthError**                      | ऑथेंटिकेशन त्रुटि।                                       |
| **onQuotaExceededError**             | इस्तेमाल की सीमा पार हो गई।                              |
| **onCommitThrottledError**           | कमिट अनुरोध थ्रॉटल किया गया।                             |
| **onTranscriberError**               | ट्रांसक्रिप्शन इंजन त्रुटि।                              |
| **onUnacceptedTermsError**           | सेवा की शर्तें स्वीकार नहीं की गईं।                      |
| **onRateLimitedError**               | रेट लिमिट लागू हुई।                                      |
| **onInputError**                     | अमान्य इनपुट फ़ॉर्मैट।                                   |
| **onQueueOverflowError**             | प्रोसेसिंग क्यू भरी हुई है।                              |
| **onResourceExhaustedError**         | सर्वर संसाधन क्षमता पर हैं।                              |
| **onSessionTimeLimitExceededError**  | अधिकतम सेशन समय पूरा हो गया।                             |
| **onChunkSizeExceededError**         | ऑडियो चंक बहुत बड़ा है।                                  |
| **onInsufficientAudioActivityError** | कनेक्शन बनाए रखने के लिए पर्याप्त ऑडियो गतिविधि नहीं है। |

## माइक्रोफ़ोन मोड

यूज़र के माइक्रोफ़ोन से सीधे ऑडियो स्ट्रीम करें:

```tsx
function MicrophoneTranscription() {
  const scribe = useScribe({
    modelId: "scribe_v2_realtime",
  });

  const startRecording = async () => {
    const token = await fetchToken();
    await scribe.connect({
      token,
      microphone: {
        echoCancellation: true,
        noiseSuppression: true,
        autoGainControl: true,
      },
    });
  };

  return (
    <div>
      <button onClick={startRecording} disabled={scribe.isConnected}>
        {scribe.status === "connecting" ? "Connecting..." : "Start"}
      </button>
      <button onClick={scribe.disconnect} disabled={!scribe.isConnected}>
        Stop
      </button>

      {scribe.partialTranscript && (
        <div>
          <strong>Speaking:</strong> {scribe.partialTranscript}
        </div>
      )}

      {scribe.committedTranscripts.map((transcript) => (
        <div key={transcript.id}>{transcript.text}</div>
      ))}
    </div>
  );
}
```

## मैन्युअल ऑडियो मोड (फ़ाइल ट्रांसक्रिप्शन)

पहले से रिकॉर्ड की गई ऑडियो फ़ाइलें ट्रांसक्राइब करें:

```tsx
import { useScribe, AudioFormat } from "@elevenlabs/react";
import { useState } from "react";

function FileTranscription() {
  const [file, setFile] = useState<File | null>(null);
  const scribe = useScribe({
    modelId: "scribe_v2_realtime",
    audioFormat: AudioFormat.PCM_16000,
    sampleRate: 16000,
  });

  const transcribeFile = async () => {
    if (!file) return;

    const token = await fetchToken();
    await scribe.connect({ token });

    // Decode audio file
    const arrayBuffer = await file.arrayBuffer();
    const audioContext = new AudioContext({ sampleRate: 16000 });
    const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);

    // Convert to PCM16
    const channelData = audioBuffer.getChannelData(0);
    const pcmData = new Int16Array(channelData.length);

    for (let i = 0; i < channelData.length; i++) {
      const sample = Math.max(-1, Math.min(1, channelData[i]));
      pcmData[i] = sample < 0 ? sample * 32768 : sample * 32767;
    }

    // Send in chunks
    const chunkSize = 4096;
    for (let offset = 0; offset < pcmData.length; offset += chunkSize) {
      const chunk = pcmData.slice(offset, offset + chunkSize);
      const bytes = new Uint8Array(chunk.buffer);
      const base64 = btoa(String.fromCharCode(...bytes));

      scribe.sendAudio(base64);
      await new Promise((resolve) => setTimeout(resolve, 50));
    }

    // Commit transcription
    scribe.commit();
  };

  return (
    <div>
      <input type="file" accept="audio/*" onChange={(e) => setFile(e.target.files?.[0] || null)} />
      <button onClick={transcribeFile} disabled={!file || scribe.isConnected}>
        Transcribe
      </button>

      {scribe.committedTranscripts.map((transcript) => (
        <div key={transcript.id}>{transcript.text}</div>
      ))}
    </div>
  );
}
```

## रिटर्न वैल्यू

### स्टेट

* **status** - मौजूदा कनेक्शन स्थिति: `"disconnected"`, `"connecting"`, `"connected"`, `"transcribing"`, या `"error"`।
* **isConnected** - कनेक्ट होने का संकेत देने वाला बूलियन।
* **isTranscribing** - सक्रिय रूप से ट्रांसक्राइब हो रहा है या नहीं, इसका संकेत देने वाला बूलियन।
* **partialTranscript** - मौजूदा आंशिक (अस्थायी) ट्रांसक्रिप्ट स्ट्रिंग।
* **committedTranscripts** - `TranscriptSegment` ऑब्जेक्ट्स की ऐरे (नीचे देखें)।
* **error** - मौजूदा एरर मैसेज या `null`।

```tsx
const scribe = useScribe(/* options */);

console.log(scribe.status); // "connected"
console.log(scribe.isConnected); // true
console.log(scribe.partialTranscript); // "hello world"
console.log(scribe.committedTranscripts); // [{ id: "...", text: "...", words: ..., isFinal: true }]
console.log(scribe.error); // null or error string
```

हर कमिट किए गए ट्रांसक्रिप्ट सेगमेंट का स्ट्रक्चर यह है:

```typescript
interface TranscriptSegment {
  id: string; // Unique identifier
  text: string; // Transcript text
  timestamp: number; // Unix timestamp
  isFinal: boolean; // Always true for committed transcripts
}
```

### मेथड्स

#### connect(options?)

Scribe से कनेक्ट करें। यहां दिए गए विकल्प हुक डिफ़ॉल्ट को ओवरराइड करते हैं:

```tsx
await scribe.connect({
  token: "your-token", // Required
  microphone: {
    /* ... */
  }, // For microphone mode
  // OR
  audioFormat: AudioFormat.PCM_16000, // For manual mode
  sampleRate: 16000,
});
```

#### disconnect()

डिस्कनेक्ट करें और संसाधन साफ़ करें:

```tsx
scribe.disconnect();
```

#### sendAudio(audioBase64, options?)

ऑडियो डेटा भेजें (सिर्फ़ मैन्युअल मोड):

```tsx
scribe.sendAudio(base64AudioChunk, {
  commit: false, // Optional: commit immediately
  sampleRate: 16000, // Optional: override sample rate
  previousText: "Previous transcription text", // Optional: context from a previous transcription. Can only be sent in the first audio chunk.
});
```

> **Warning**
>
> `previousText` फ़ील्ड सिर्फ़ सेशन के पहले ऑडियो चंक में भेजी जा सकती है। इसे
> बाद के चंक्स में भेजने पर एरर आता है।

#### commit()

मौजूदा ट्रांसक्रिप्शन को मैन्युअल रूप से कमिट करें:

```tsx
scribe.commit();
```

#### clearTranscripts()

स्टेट से सभी ट्रांसक्रिप्ट साफ़ करें:

```tsx
scribe.clearTranscripts();
```

#### getConnection()

अंडरलाइंग कनेक्शन इंस्टेंस पाएं:

```tsx
const connection = scribe.getConnection();
// Returns RealtimeConnection | null
```

## कमिट स्ट्रैटेजी

ट्रांसक्रिप्शन कब कमिट हों, यह नियंत्रित करें:

```tsx
import { CommitStrategy } from '@elevenlabs/react';

// Manual (default) - you control when to commit
const scribe = useScribe({
  commitStrategy: CommitStrategy.MANUAL,
});

// Later...
scribe.commit(); // Commit transcription

// Voice Activity Detection - model detects silences and automatically commits
const scribe = useScribe({
  commitStrategy: CommitStrategy.VAD,
});
```

ज़्यादा जानकारी के लिए [ट्रांसक्रिप्ट और कमिट स्ट्रैटेजी](/docs/hi/eleven-api/guides/how-to/speech-to-text/realtime/transcripts-and-commit-strategies) देखें।

## पूरा उदाहरण

यह VAD-आधारित कमिट स्ट्रैटेजी के साथ `useScribe` हुक इस्तेमाल करने वाले React कंपोनेंट का पूरा उदाहरण है:

```tsx
import { useScribe, CommitStrategy } from "@elevenlabs/react";
import { useEffect } from "react";

function ScribeDemo() {
  const scribe = useScribe({
    modelId: "scribe_v2_realtime",
    commitStrategy: CommitStrategy.VAD,
    onSessionStarted: () => console.log("Started"),
    onCommittedTranscript: (data) => console.log("Committed:", data.text),
    onError: (error) => console.error("Error:", error),
  });

  const startMicrophone = async () => {
    const token = await fetchToken();
    await scribe.connect({
      token,
      microphone: {
        echoCancellation: true,
        noiseSuppression: true,
      },
    });
  };

  const handleDisconnect = () => scribe.disconnect();

  const handleClearTranscripts = () => scribe.clearTranscripts();

  useEffect(() => {
    return () => {
      handleDisconnect();
    };
  }, []);

  return (
    <div>
      <h1>Scribe Demo</h1>

      {/* Status */}
      <div>
        Status: {scribe.status}
        {scribe.error && <span>Error: {scribe.error}</span>}
      </div>

      {/* Controls */}
      <div>
        {!scribe.isConnected ? (
          <button onClick={startMicrophone}>Start Recording</button>
        ) : (
          <button onClick={handleDisconnect}>Stop</button>
        )}
        <button onClick={handleClearTranscripts}>Clear</button>
      </div>

      {/* Live Transcript */}
      {scribe.partialTranscript && (
        <div>
          <strong>Live:</strong> {scribe.partialTranscript}
        </div>
      )}

      {/* Committed Transcripts */}
      <div>
        <h2>Transcripts ({scribe.committedTranscripts.length})</h2>
        {scribe.committedTranscripts.map((t) => (
          <div key={t.id}>
            <span>{new Date(t.timestamp).toLocaleTimeString()}</span>
            <p>{t.text}</p>
          </div>
        ))}
      </div>
    </div>
  );
}
```