# Seslendirme ve sesler

> Metni istediğiniz biçimde sese çevirin, bir modelin seslerini listeleyin ve konuşmacının rızasıyla projeniz için bir ses klonlayın.

`POST /audio/speech` metni sese çevirir. İstek OpenAI ile uyumludur; OpenAI SDK'larının `audio.speech.create` yöntemi bu uçla çalışır. Sesler [`GET /audio/voices`](https://www.getlykia.com/docs/api-reference/audio-voices-list) ile gelir; proje [`POST /audio/voices`](https://www.getlykia.com/docs/api-reference/audio-voices-create) ile kendi klonlanmış seslerini ekleyebilir. Alan alan başvuru: [POST /audio/speech](https://www.getlykia.com/docs/api-reference/audio-speech).

## Seslendirme üretin

**cURL**

```bash
curl https://api.getlykia.com/v1/audio/speech \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini-tts",
    "input": "Your order has shipped and will arrive on Thursday.",
    "voice": "alloy",
    "response_format": "mp3"
  }' \
  --output speech.mp3
```

**Python**

```python
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

with client.audio.speech.with_streaming_response.create(
    model="openai/gpt-4o-mini-tts",
    input="Your order has shipped and will arrive on Thursday.",
    voice="alloy",
    response_format="mp3",
) as response:
    # The cost is known before the audio starts, so it comes as a header
    print("cost (USD):", response.headers.get("X-Lykia-Cost"))
    response.stream_to_file("speech.mp3")
```

**TypeScript**

```typescript
import { writeFile } from "node:fs/promises";

const response = await fetch("https://api.getlykia.com/v1/audio/speech", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.LYKIA_API_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "openai/gpt-4o-mini-tts",
    input: "Your order has shipped and will arrive on Thursday.",
    voice: "alloy",
    response_format: "mp3",
  }),
});
if (!response.ok) throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);

// The cost is known before the audio starts, so it comes as a header
console.log("cost (USD):", response.headers.get("X-Lykia-Cost"), "id:", response.headers.get("X-Generation-Id"));
await writeFile("speech.mp3", Buffer.from(await response.arrayBuffer()));
```

Yanıt gövdesi sesin kendisidir; üretildikçe akar. `Content-Type` `response_format`'a uyar: `mp3` (varsayılan), `opus`, `aac`, `flac`, `wav` ya da `pcm`. Bir modelin desteklediği biçimler [`GET /models?kind=speech`](https://www.getlykia.com/docs/api-reference/models) yanıtındaki `media.capabilities.speech.formats` alanındadır.

Seslendirme `input`'un karakteri başına (sağlayıcısı token faturalayan modellerde token başına) fiyatlanır; bu yüzden maliyet ses başlamadan bilinir: `X-Lykia-Cost` başlığında, istek kimliğini taşıyan `X-Generation-Id`'nin yanında gelir. Bağlantı yarıda koparsa sağlayıcının faturaladığı karakterler yine tahsil edilir.

Diğer alanlar: `speed` (modelin `speech.speed` aralığında), `language` ve konuşma tarzı alan modellerde (`speech.instructions`) `instructions`. Bir modelin kabul ettiği en uzun `input` `speech.maxInputChars`'tır.

## Sesleri listeleyin

`voice` bir ses kimliğidir. `GET /audio/voices?model=…` modelin hazır seslerini ve projenizin o model için klonladığı sesleri listeler:

**cURL**

```bash
curl "https://api.getlykia.com/v1/audio/voices?model=openai/gpt-4o-mini-tts" \
  -H "Authorization: Bearer $LYKIA_API_KEY"
```

**Python**

```python
import os

import requests

response = requests.get(
    "https://api.getlykia.com/v1/audio/voices",
    headers={"Authorization": f"Bearer {os.environ['LYKIA_API_KEY']}"},
    params={"model": "elevenlabs/eleven_multilingual_v2"},
    timeout=30,
)
response.raise_for_status()
for voice in response.json()["data"]:
    print(voice["id"], voice["name"], voice["category"])
```

**TypeScript**

```typescript
const params = new URLSearchParams({ model: "elevenlabs/eleven_multilingual_v2" });
const response = await fetch(`https://api.getlykia.com/v1/audio/voices?${params}`, {
  headers: { Authorization: `Bearer ${process.env.LYKIA_API_KEY}` },
});
if (!response.ok) throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);

const voices = (await response.json()) as { data: { id: string; name: string; category: string }[] };
for (const voice of voices.data) console.log(voice.id, voice.name, voice.category);
```

```json
{
    "object": "list",
    "model": "openai/gpt-4o-mini-tts",
    "provider": "openai",
    "data": [
        {
            "id": "alloy",
            "object": "voice",
            "name": "Alloy",
            "category": "premade",
            "provider": "openai"
        },
        {
            "id": "ash",
            "object": "voice",
            "name": "Ash",
            "category": "premade",
            "provider": "openai"
        },
        {
            "id": "coral",
            "object": "voice",
            "name": "Coral",
            "category": "premade",
            "provider": "openai"
        }
    ]
}
```

`model` verilmezse liste `@tts` hazır ayarınızın modeli içindir.

## Ses klonlayın

Bazı modeller kısa bir kayıttan klonlanan bir sesle konuşabilir. Konuşmacının bir ya da birkaç kaydını `multipart/form-data` olarak, ses için bir `name` ve `consent=true` ile gönderin:

**cURL**

```bash
# consent=true confirms that you have the speaker's permission to clone this voice
curl https://api.getlykia.com/v1/audio/voices \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -F model=elevenlabs/eleven_multilingual_v2 \
  -F name="Store narrator" \
  -F description="Calm narration voice" \
  -F consent=true \
  -F file=@sample.mp3
```

**Python**

```python
import os

import requests

with open("sample.mp3", "rb") as sample:
    response = requests.post(
        "https://api.getlykia.com/v1/audio/voices",
        headers={"Authorization": f"Bearer {os.environ['LYKIA_API_KEY']}"},
        data={
            "model": "elevenlabs/eleven_multilingual_v2",
            "name": "Store narrator",
            # You confirm that you have the speaker's permission to clone this voice
            "consent": "true",
        },
        files={"file": ("sample.mp3", sample, "audio/mpeg")},
        timeout=120,
    )
response.raise_for_status()
voice = response.json()
print(voice["id"], voice["name"])  # use the id as `voice` in speech requests of this project
```

**TypeScript**

```typescript
import { readFile } from "node:fs/promises";

const form = new FormData();
form.append("model", "elevenlabs/eleven_multilingual_v2");
form.append("name", "Store narrator");
// You confirm that you have the speaker's permission to clone this voice
form.append("consent", "true");
form.append("file", new Blob([await readFile("sample.mp3")], { type: "audio/mpeg" }), "sample.mp3");

const response = await fetch("https://api.getlykia.com/v1/audio/voices", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.LYKIA_API_KEY}` },
  body: form,
});
if (!response.ok) throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);

const voice = (await response.json()) as { id: string; name: string };
console.log(voice.id, voice.name); // use the id as `voice` in speech requests of this project
```

> **Rıza zorunludur:** Yalnız kullanma hakkınız olan bir sesi klonlayın: kendi sesinizi ya da size sesini klonlama izni vermiş birinin sesini. `consent=true` bu izne sahip olduğunuzu beyan etmenizdir; Lykia bu beyan olmadan isteği reddeder (`400`, `consent_required`) ve beyanı API anahtarınız ve projenizle birlikte kayda geçirir.

Yanıt, kimliği `lvc_` ile başlayan bir ses nesnesidir:

```json
{
    "id": "lvc_xg3eZdWjqZ19YY04ozRw",
    "object": "voice",
    "name": "Narrator",
    "category": "cloned",
    "description": "Calm narration voice",
    "provider": "elevenlabs",
    "model": "elevenlabs/eleven_multilingual_v2",
    "created_at": 1795463459,
    "requires_verification": false
}
```

Bu kimliği seslendirme isteklerinde `voice` olarak kullanın. Klonlanmış ses onu oluşturan projeye aittir: yalnız o projenin anahtarlarıyla, oluşturulduğu sağlayıcı ve aynı anahtarla (Lykia'nınki ya da sizinki) çalışır; başka projelerin istekleri `404` (`voice_not_found`) alır. Klonlamanın kendisi ücretlendirilmez; bu sesle seslendirme diğer seslendirme istekleri gibi fiyatlanır. Bazı sağlayıcılar klonun kullanılmadan önce konuşmacı tarafından doğrulanmasını ister; `requires_verification` bunu söyler.

## Klonlanmış sesi silin

`DELETE /audio/voices/{id}` klonu sağlayıcıda ve Lykia'da siler:

**cURL**

```bash
curl -X DELETE https://api.getlykia.com/v1/audio/voices/lvc_xg3eZdWjqZ19YY04ozRw \
  -H "Authorization: Bearer $LYKIA_API_KEY"
```

**Python**

```python
import os

import requests

VOICE_ID = "lvc_xg3eZdWjqZ19YY04ozRw"

response = requests.delete(
    f"https://api.getlykia.com/v1/audio/voices/{VOICE_ID}",
    headers={"Authorization": f"Bearer {os.environ['LYKIA_API_KEY']}"},
    timeout=60,
)
response.raise_for_status()
print(response.json()["deleted"])
```

## Hatalar

| Kod                       | Durum | Ne zaman                                                                                                                    |
| ------------------------- | ----- | --------------------------------------------------------------------------------------------------------------------------- |
| `unsupported_input`       | `400` | Desteklenmeyen `response_format` ya da `speed`, ya da modelin aldığından uzun `input`. `metadata.param` alanın adını verir. |
| `consent_required`        | `400` | `POST /audio/voices` isteğinde `consent=true` yok.                                                                          |
| `platform_sales_disabled` | `403` | Modelin sağlayıcısı henüz Lykia kredisiyle sunulmuyor. Projeye o sağlayıcının kendi anahtarınızı ekleyin.                   |
| `voice_not_found`         | `404` | Ses kimliği bilinmiyor ya da başka bir projeye ait.                                                                         |
| `provider_busy`           | `429` | Lykia'nın sağlayıcıyla bağlantısı aynı anda alabileceği istek sınırında. `Retry-After` kadar bekleyip yeniden deneyin.      |

Hata gövdesi ve diğer durum kodları için [Hatalar](https://www.getlykia.com/docs/guides/errors) sayfasına bakın.
