> 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.

# रीयल-टाइम में ऑडियो जनरेट करें

WebSocket स्ट्रीमिंग एक ही, लंबे समय तक चलने वाले कनेक्शन पर डेटा भेजने और प्राप्त करने का तरीका है। यह तरीका रीयल-टाइम ऐप्लिकेशन के लिए उपयोगी है, जहाँ उपलब्ध होते ही आपको ऑडियो डेटा स्ट्रीम करना होता है।

अगर आप ElevenLabs टेक्स्ट टू स्पीच API के WebSocket कनेक्शन की लेटेंसी (पहला बाइट मिलने का समय) जल्दी से टेस्ट करना चाहते हैं, तो आप `npm` के ज़रिए `elevenlabs-latency` इंस्टॉल कर सकते हैं और [यहाँ](https://www.npmjs.com/package/elevenlabs-latency?activeTab=readme) दिए निर्देशों का पालन कर सकते हैं।

> **Note**
>
> WebSockets टेक्स्ट टू स्पीच और Agents Platform के लिए उपलब्ध हैं। यह गाइड **टेक्स्ट
> टू स्पीच** WebSocket (`/v1/text-to-speech/{voice_id}/stream-input`) के बारे में है। यह endpoint **नहीं**
> `eleven_v3` या `eleven_v4` मॉडल सपोर्ट करता है। WebSocket पर **Eleven v3** या **Eleven v4** डायलॉग के लिए,
> [रीयलटाइम टेक्स्ट टू डायलॉग](/docs/hi/eleven-api/guides/how-to/websockets/realtime-tdd)
> और [टेक्स्ट टू स्पीच बनाम टेक्स्ट टू डायलॉग WebSockets](/docs/hi/eleven-api/guides/how-to/websockets/tts-vs-ttd-websockets) देखें।

## आवश्यकताएँ

* API key वाला ElevenLabs अकाउंट (अपनी [API key कैसे ढूँढें](/docs/hi/api-reference/authentication), यहाँ जानें)।
* आपकी मशीन पर Python या Node.js (या कोई अन्य JavaScript runtime) इंस्टॉल होना चाहिए

## सेटअप

ज़रूरी dependencies इंस्टॉल करें:

**`Python`**

```python Python
pip install python-dotenv
pip install websockets
```

**`TypeScript`**

```typescript TypeScript
npm install dotenv
npm install @types/dotenv --save-dev
npm install ws
```

अब अपनी प्रोजेक्ट डायरेक्टरी में `.env` फ़ाइल बनाएँ और अपनी API key जोड़ें:

**`.env`**

```bash .env
ELEVENLABS_API_KEY=your_elevenlabs_api_key_here
```

## WebSocket कनेक्शन शुरू करें

वॉइस लाइब्रेरी से वॉइस और इस्तेमाल करने के लिए टेक्स्ट टू स्पीच मॉडल चुनने के बाद, टेक्स्ट टू स्पीच API से WebSocket कनेक्शन शुरू करें।

**`text-to-speech-websocket.py`**

```python text-to-speech-websocket.py
import os
from dotenv import load_dotenv
import websockets

# Load the API key from the .env file
load_dotenv()
ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")

voice_id = 'Xb7hH8MSUJpSbSDYk0k2'

# For use cases where latency is important, we recommend using the 'eleven_flash_v2_5' model.
model_id = 'eleven_flash_v2_5'

async def text_to_speech_ws_streaming(voice_id, model_id):
    uri = f"wss://api.elevenlabs.io/v1/text-to-speech/{voice_id}/stream-input?model_id={model_id}"

    async with websockets.connect(uri) as websocket:
       ...
```

**`text-to-speech-websocket.ts`**

```typescript text-to-speech-websocket.ts
import * as dotenv from "dotenv";
import * as fs from "node:fs";
import WebSocket from "ws";

// Load the API key from the .env file
dotenv.config();
const ELEVENLABS_API_KEY = process.env.ELEVENLABS_API_KEY;

const voiceId = "Xb7hH8MSUJpSbSDYk0k2";

// For use cases where latency is important, we recommend using the 'eleven_flash_v2_5' model.
const model = "eleven_flash_v2_5";

const uri = `wss://api.elevenlabs.io/v1/text-to-speech/${voiceId}/stream-input?model_id=${model}`;
const websocket = new WebSocket(uri, {
  headers: { "xi-api-key": `${ELEVENLABS_API_KEY}` },
});

// Create a directory for saving the audio
const outputDir = "./output";

try {
  fs.accessSync(outputDir, fs.constants.R_OK | fs.constants.W_OK);
} catch (err) {
  fs.mkdirSync(outputDir);
}

// Create a write stream for saving the audio into mp3
const writeStream = fs.createWriteStream(outputDir + "/test.mp3", {
  flags: "a",
});
```

## इनपुट टेक्स्ट भेजें

WebSocket कनेक्शन खुलने के बाद, पहले वॉइस सेटिंग्स सेट करें। फिर API को टेक्स्ट मैसेज भेजें।

**`text-to-speech-websocket.py`**

```python text-to-speech-websocket.py
async def text_to_speech_ws_streaming(voice_id, model_id):
    async with websockets.connect(uri) as websocket:
        await websocket.send(json.dumps({
            "text": " ",
            "voice_settings": {"stability": 0.5, "similarity_boost": 0.8, "use_speaker_boost": False},
            "generation_config": {
                "chunk_length_schedule": [120, 160, 250, 290]
            },
            "xi_api_key": ELEVENLABS_API_KEY,
        }))

        text = "The twilight sun cast its warm golden hues upon the vast rolling fields, saturating the landscape with an ethereal glow. Silently, the meandering brook continued its ceaseless journey, whispering secrets only the trees seemed privy to."
        await websocket.send(json.dumps({"text": text}))

        # Send empty string to indicate the end of the text sequence which will close the WebSocket connection
        await websocket.send(json.dumps({"text": ""}))
```

**`text-to-speech-websocket.ts`**

```typescript text-to-speech-websocket.ts
const text =
  "The twilight sun cast its warm golden hues upon the vast rolling fields, saturating the landscape with an ethereal glow. Silently, the meandering brook continued its ceaseless journey, whispering secrets only the trees seemed privy to.";

websocket.on("open", async () => {
  websocket.send(
    JSON.stringify({
      text: " ",
      voice_settings: {
        stability: 0.5,
        similarity_boost: 0.8,
        use_speaker_boost: false,
      },
      generation_config: { chunk_length_schedule: [120, 160, 250, 290] },
    })
  );

  websocket.send(JSON.stringify({ text: text }));

  // Send empty string to indicate the end of the text sequence which will close the websocket connection
  websocket.send(JSON.stringify({ text: "" }));
});
```

## ऑडियो को फ़ाइल में सेव करें

WebSocket कनेक्शन से आने वाले मैसेज को पढ़ें और ऑडियो चंक्स को लोकल फ़ाइल में लिखें।

**`text-to-speech-websocket.py`**

```python text-to-speech-websocket.py
import asyncio

async def write_to_local(audio_stream):
    """Write the audio encoded in base64 string to a local mp3 file."""

    with open(f'./output/test.mp3', "wb") as f:
        async for chunk in audio_stream:
            if chunk:
                f.write(chunk)

async def listen(websocket):
    """Listen to the websocket for audio data and stream it."""

    while True:
        try:
            message = await websocket.recv()
            data = json.loads(message)
            if data.get("audio"):
                yield base64.b64decode(data["audio"])
            elif data.get('isFinal'):
                break

        except websockets.exceptions.ConnectionClosed:
            print("Connection closed")
            break

async def text_to_speech_ws_streaming(voice_id, model_id):
    async with websockets.connect(uri) as websocket:
          ...
          # Add listen task to submit the audio chunks to the write_to_local function
          listen_task = asyncio.create_task(write_to_local(listen(websocket)))

          await listen_task

asyncio.run(text_to_speech_ws_streaming(voice_id, model_id))
```

**`text-to-speech-websocket.ts`**

```typescript text-to-speech-websocket.ts
// Helper function to write the audio encoded in base64 string into local file
function writeToLocal(base64str: any, writeStream: fs.WriteStream) {
  const audioBuffer: Buffer = Buffer.from(base64str, "base64");
  writeStream.write(audioBuffer, (err) => {
    if (err) {
      console.error("Error writing to file:", err);
    }
  });
}

// Listen to the incoming message from the websocket connection
websocket.on("message", function incoming(event) {
  const data = JSON.parse(event.toString());
  if (data["audio"]) {
    writeToLocal(data["audio"], writeStream);
  }
});

// Close the writeStream when the websocket connection closes
websocket.on("close", () => {
  writeStream.end();
});
```

## स्क्रिप्ट चलाएँ

टर्मिनल में नीचे दिया कमांड चलाकर आप स्क्रिप्ट चला सकते हैं। `output` डायरेक्टरी में एक mp3 ऑडियो फ़ाइल सेव हो जाएगी।

**`Python`**

```python Python
python text-to-speech-websocket.py
```

**`TypeScript`**

```typescript TypeScript
npx tsx text-to-speech-websocket.ts
```

## एडवांस्ड कॉन्फ़िगरेशन

WebSockets के साथ कुछ एडवांस्ड सेटिंग्स मिलती हैं, जिनसे आप अपनी रीयल-टाइम ऑडियो जनरेशन को बेहतर ढंग से ट्यून कर सकते हैं।

### बफ़रिंग

रीयल-टाइम ऑडियो जनरेट करते समय, दो अहम कॉन्सेप्ट ध्यान में रखने चाहिए: Time To First Byte (TTFB) और बफ़रिंग। उच्च-गुणवत्ता ऑडियो बनाने और संदर्भ समझने के लिए मॉडल को एक निश्चित मात्रा में इनपुट टेक्स्ट चाहिए। WebSocket कनेक्शन में जितना अधिक टेक्स्ट भेजा जाता है, ऑडियो क्वालिटी उतनी ही बेहतर होती है। अगर यह सीमा पूरी नहीं होती, तो मॉडल टेक्स्ट को बफ़र में जोड़ देता है और बफ़र भरने पर ऑडियो जनरेट करता है।

लेटेंसी के संदर्भ में, TTFB वह समय है जो ऑडियो का पहला बाइट क्लाइंट तक भेजने में लगता है। यह अहम है क्योंकि इससे ऑडियो की महसूस होने वाली लेटेंसी प्रभावित होती है। इसलिए, क्वालिटी और लेटेंसी के बीच संतुलन बनाने के लिए आप बफ़र साइज़ नियंत्रित करना चाह सकते हैं।

इसे मैनेज करने के लिए, WebSocket कनेक्शन शुरू करते समय या टेक्स्ट भेजते समय आप `chunk_length_schedule` पैरामीटर इस्तेमाल कर सकते हैं। यह पैरामीटर integers की एक array है, जो ऑडियो जनरेट करने से पहले मॉडल को भेजे जाने वाले अक्षरों की संख्या बताती है। उदाहरण के लिए, अगर आप `chunk_length_schedule` को `[120, 160, 250, 290]` पर सेट करते हैं, तो मॉडल क्रमशः 120, 160, 250 और 290 अक्षर भेजे जाने के बाद ऑडियो जनरेट करेगा।

यहाँ `chunk_length_schedule` की डिफ़ॉल्ट सेटिंग्स के साथ इसका एक उदाहरण है:

![](/docs/_fern-img/077efc232570b0f92355aed2d6766b66bba815e335466e81cd64f8dfcce10ada.webp)

ऊपर दिए डायग्राम में, सर्वर को दूसरा मैसेज भेजने के बाद ही ऑडियो जनरेट होता है। ऐसा इसलिए है क्योंकि पहला मैसेज 120 अक्षरों की सीमा से कम है, जबकि दूसरा मैसेज कुल अक्षरों की संख्या को सीमा से ऊपर ले जाता है। तीसरा मैसेज 160 अक्षरों की सीमा से अधिक है, इसलिए ऑडियो तुरंत जनरेट होकर क्लाइंट को भेज दिया जाता है।

WebSocket कनेक्शन शुरू करते समय या टेक्स्ट भेजते समय आप `chunk_length_schedule` के लिए कस्टम वैल्यू दे सकते हैं।

```python
await websocket.send(json.dumps({
    "text": text,
    "generation_config": {
        # Generate audio after 50, 120, 160, and 290 characters have been sent
        "chunk_length_schedule": [50, 120, 160, 290]
    },
    "xi_api_key": ELEVENLABS_API_KEY,
}))
```

```typescript
websocket.send(
  JSON.stringify({
    text: text,
    // Generate audio after 50, 120, 160, and 290 characters have been sent
    generation_config: { chunk_length_schedule: [50, 120, 160, 290] },
    xi_api_key: ELEVENLABS_API_KEY,
  })
);
```

अगर आप ऑडियो को तुरंत वापस पाना चाहते हैं, तो बफ़र साफ़ करने और बफ़र किए गए किसी भी टेक्स्ट का ऑडियो तुरंत जनरेट करने के लिए `flush: true` इस्तेमाल कर सकते हैं। उदाहरण के लिए, जब आप किसी दस्तावेज़ के अंत तक पहुँच जाएँ और अंतिम सेक्शन का ऑडियो जनरेट करना चाहें, तब यह उपयोगी हो सकता है।

![](/docs/_fern-img/84011e01024effe1bba1556f0007c7947165a0101bce3a41f8b955d1a9788a9c.webp)

मैसेज में `flush: true` सेट करके इसे हर मैसेज के लिए अलग-अलग निर्दिष्ट किया जा सकता है।

```python
await websocket.send(json.dumps({"text": "Generate this audio immediately.", "flush": True}))
```

```typescript
websocket.send(JSON.stringify({ text: "Generate this audio immediately.", flush: true }));
```

इसके अलावा, websocket बंद करने पर बफ़र किया गया कोई भी टेक्स्ट अपने-आप जनरेट हो जाएगा।

### वॉइस सेटिंग्स

WebSocket कनेक्शन शुरू करते समय, आप बाद की जनरेशन के लिए वॉइस सेटिंग्स तय कर सकते हैं। इससे आप जनरेट किए गए ऑडियो की स्पीड, स्थिरता और वॉइस की अन्य विशेषताओं को नियंत्रित कर सकते हैं।

```python
await websocket.send(json.dumps({
    "text": text,
    "voice_settings": {"stability": 0.5, "similarity_boost": 0.8, "use_speaker_boost": False},
}))
```

```typescript
websocket.send(
  JSON.stringify({
    text: text,
    voice_settings: { stability: 0.5, similarity_boost: 0.8, use_speaker_boost: false },
  })
);
```

मैसेज में अलग `voice_settings` देकर इसे हर मैसेज के लिए ओवरराइड किया जा सकता है।

### उच्चारण डिक्शनरी

आप खास शब्दों या वाक्यांशों के उच्चारण को नियंत्रित करने के लिए उच्चारण डिक्शनरी इस्तेमाल कर सकते हैं। यह सुनिश्चित करने के लिए उपयोगी है कि कुछ शब्दों का सही उच्चारण हो या कुछ शब्दों अथवा वाक्यांशों पर ज़ोर दिया जाए।

`voice_settings` और `generation_config` के विपरीत, उच्चारण डिक्शनरी को "Initialize Connection" मैसेज में देना ज़रूरी है। अधिक जानकारी के लिए [API रेफरेंस](/docs/hi/api-reference/text-to-speech/v-1-text-to-speech-voice-id-stream-input#send.Initialize%20Connection.pronunciation_dictionary_locators) देखें।

> **Tip**
>
> WebSockets के साथ phoneme-आधारित उच्चारण डिक्शनरी इस्तेमाल करते समय, आपको WebSocket URI में query parameter के रूप में `enable_ssml_parsing=true` जोड़ना होगा। उदाहरण:
>
> ```
> wss://api.elevenlabs.io/v1/text-to-speech/{voice_id}/stream-input?model_id={model_id}&enable_ssml_parsing=true
> ```

## सर्वोत्तम तरीका

* हम `generation_config` में `chunk_length_schedule` की डिफ़ॉल्ट सेटिंग इस्तेमाल करने का सुझाव देते हैं।
* रीयल-टाइम कन्वर्सेशनल एजेंट ऐप्लिकेशन बनाते समय, समय पर ऑडियो जनरेशन सुनिश्चित करने के लिए बातचीत के टर्न के अंत में टेक्स्ट के साथ `flush: true` इस्तेमाल करें।
* अगर डिफ़ॉल्ट सेटिंग आपके उपयोग के लिए सबसे अच्छी लेटेंसी नहीं देती है, तो आप `chunk_length_schedule` बदल सकते हैं। हालाँकि, ध्यान रखें कि इस बदलाव से लेटेंसी कम करने पर क्वालिटी प्रभावित हो सकती है।

## सुझाव

* निष्क्रियता के 20 सेकंड बाद WebSocket कनेक्शन अपने-आप बंद हो जाएगा। कनेक्शन खुला रखने के लिए, आप एक single space character `" "` भेज सकते हैं। ध्यान रखें कि इस स्ट्रिंग में space शामिल होना चाहिए, क्योंकि पूरी तरह खाली स्ट्रिंग, `""`, भेजने से WebSocket बंद हो जाएगा।
* आखिरी टेक्स्ट मैसेज भेजने के बाद WebSocket कनेक्शन बंद करने के लिए एक खाली स्ट्रिंग भेजें।
* टेक्स्ट के हर शब्द के लिए शब्द-स्तरीय timestamps पाने के लिए आप `alignment` इस्तेमाल कर सकते हैं। यह वीडियो में ऑडियो को टेक्स्ट के साथ संरेखित करने या सटीक टाइमिंग वाले अन्य ऐप्लिकेशन के लिए उपयोगी हो सकता है। अधिक जानकारी के लिए [API रेफरेंस](/docs/hi/api-reference/text-to-speech/v-1-text-to-speech-voice-id-stream-input#receive.Audio%20Output.alignment) देखें।

## अगले चरण

#### [TTS स्ट्रीमिंग](/docs/hi/eleven-api/guides/how-to/text-to-speech/streaming)

जब इनपुट टेक्स्ट रीयल टाइम में जनरेट होने के बजाय पहले से उपलब्ध हो, तो HTTP स्ट्रीमिंग इस्तेमाल करें।

#### [लेटेंसी ऑप्टिमाइज़ेशन](/docs/hi/eleven-api/guides/how-to/best-practices/latency-optimization)

मॉडल चयन, वॉइस चयन और भौगोलिक रूटिंग से पहले ऑडियो तक का समय कम करें।