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

# Fala

> Transcreva áudio e gere fala com a API MKA1. Use segmentos rotulados por locutor quando precisar de separação de múltiplos falantes.

Use os endpoints de fala da API MKA1 quando precisar de conversão de fala para texto ou texto para fala baseada em arquivos.
Para sessões de voz bidirecionais em tempo real, use o [Modo de voz avançado](/pt/docs/advanced-voice-mode).

## Escolha o endpoint correto

| Caso de uso                                 | Endpoint                                                                                | Observações                                    |
| ------------------------------------------- | --------------------------------------------------------------------------------------- | ---------------------------------------------- |
| Transcrever um arquivo gravado              | [Transcrição de fala para texto](/pt/api-reference/speech/speech-to-text-transcription) | Faça upload do áudio com `multipart/form-data` |
| Gerar um arquivo WAV a partir de texto      | [Texto para fala](/pt/api-reference/speech/text-to-speech)                              | Melhor para geração de arquivo completo        |
| Iniciar reprodução assim que o áudio chegar | [Texto para fala em streaming](/pt/api-reference/speech/streaming-text-to-speech)       | Melhor para reprodução de baixa latência       |

## Transcrever áudio

Envie um arquivo de áudio para o endpoint de transcrição quando quiser obter texto a partir de um arquivo gravado.
Se seu aplicativo atua em nome de um usuário final, envie também o cabeçalho `X-On-Behalf-Of`.

Formatos de áudio suportados: `FLAC`, `MP3`, `MP4`, `MPEG`, `MPGA`, `M4A`, `OGG`, `WAV`, `WebM`, `PCM`.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm speech transcribe \
    --file ./episode.wav \
    --language en \
    --prompt 'This is a technical podcast about machine learning.' \
    --temperature 0.2 \
    -H 'X-On-Behalf-Of: <end-user-id>'
  ```

  ```ts MKA1 SDK theme={null}
  import { SDK } from '@meetkai/mka1';
  import { openAsBlob } from 'node:fs';

  const mka1 = new SDK({
    bearerAuth: 'Bearer <mka1-api-key>',
  });

  const result = await mka1.llm.speech.transcribe({
    language: 'en',
    prompt: 'This is a technical podcast about machine learning.',
    temperature: 0.2,
    requestBody: {
      file: await openAsBlob('episode.wav'),
    },
  }, { headers: { 'X-On-Behalf-Of': '<end-user-id>' } });

  console.log(result.text);
  console.log(result.language);
  console.log(result.confidence);
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;
  using MeetKai.MKA1.Types.Requests;

  var sdk = new SDK(bearerAuth: "Bearer YOUR_API_KEY");

  var result = await sdk.Llm.Speech.TranscribeAsync(new TranscribeRequest()
  {
      Language = "en",
      Prompt = "This is a technical podcast about machine learning.",
      Temperature = 0.2,
      Body = new TranscribeRequestBody()
      {
          File = new TranscribeFile()
          {
              FileName = "episode.wav",
              Content = File.ReadAllBytes("episode.wav"),
          },
      },
  });

  Console.WriteLine(result.TranscriptionResponse!.Text);
  Console.WriteLine(result.TranscriptionResponse!.Language);
  Console.WriteLine(result.TranscriptionResponse!.Confidence);
  ```

  ```python Python SDK theme={null}
  from mka1 import SDK

  sdk = SDK(bearer_auth="Bearer YOUR_API_KEY")

  result = sdk.llm.speech.transcribe(
      file={"file_name": "episode.wav", "content": open("episode.wav", "rb")},
      language="en",
      prompt="This is a technical podcast about machine learning.",
      temperature=0.2,
  )

  print(result.text)
  print(result.language)
  print(result.confidence)
  ```

  ```bash bash theme={null}
  curl 'https://apigw.mka1.com/api/v1/llm/speech/transcriptions?language=en&prompt=This%20is%20a%20technical%20podcast%20about%20machine%20learning.&temperature=0.2' \
    --request POST \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --form 'file=@episode.wav'
  ```
</CodeGroup>

A resposta inclui o texto transcrito, além do idioma detectado e confiança:

```json theme={null}
{
  "text": "Hello! We're excited to show you our native speech capabilities.",
  "language": "en",
  "confidence": 0.8429018476208717
}
```

## Separar falantes em uma transcrição

Se você precisa de diarização, ative os dados de locutor na requisição de transcrição.
Quando ativado, a resposta pode incluir um array `speakers` com segmentos rotulados por locutor e metadados de tempo.

<Warning>
  Para `include_speaker_data`, envie áudio WAV ou PCM para transcrição não em streaming. Outros formatos de áudio retornam `400 BAD_REQUEST` com a mensagem `Speaker diarization currently requires WAV/PCM audio for non-streaming transcription`.
</Warning>

```ts theme={null}
const result = await mka1.llm.speech.transcribe({
  language: 'en',
  includeSpeakerData: true,
  prompt: 'This is a short podcast clip about AI product updates.',
  temperature: 0.2,
  requestBody: {
    file: await openAsBlob('panel.wav'),
  },
}, { headers: { 'X-On-Behalf-Of': '<end-user-id>' } });

console.log(result.speakers);
```

Exemplo de resposta com separação de falantes:

```json theme={null}
{
  "text": "Welcome back to the show. Today we're looking at how speech APIs fit into production apps. We'll keep it practical and focus on latency, accuracy, and speaker turns.",
  "language": "en",
  "confidence": 0.91177404,
  "speakers": [
    {
      "speaker": "Speaker-1",
      "text": "Welcome back to the show.",
      "confidence": 0.91177404,
      "offset_ms": 80,
      "duration_ms": 1280
    },
    {
      "speaker": "Speaker-2",
      "text": "Today we're looking at how speech APIs fit into production apps.",
      "confidence": 0.91177404,
      "offset_ms": 1540,
      "duration_ms": 3380
    },
    {
      "speaker": "Speaker-1",
      "text": "We'll keep it practical and focus on latency, accuracy, and speaker turns.",
      "confidence": 0.91177404,
      "offset_ms": 5220,
      "duration_ms": 3660
    }
  ]
}
```

Use o campo `text` de nível superior quando precisar de uma transcrição única e mesclada.
Use `speakers` quando precisar de legendas, alternância de turnos ou análises de falantes posteriores.

## Gerar fala

Use o endpoint padrão de texto para fala quando quiser um arquivo WAV completo.
O corpo da resposta é áudio binário, e os cabeçalhos da resposta incluem `X-Language-Code`.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm speech speak \
    --text 'Welcome to the MKA1 API speech guide.' \
    --language en \
    --output-file speech.wav
  ```

  ```ts MKA1 SDK theme={null}
  import { writeFileSync } from 'node:fs';

  const result = await mka1.llm.speech.speak({
    text: 'Welcome to the MKA1 API speech guide.',
    language: 'en',
  }, { headers: { 'X-On-Behalf-Of': '<end-user-id>' } });

  const audioBody = result.body as Blob | Uint8Array;
  const audioBuffer = audioBody instanceof Uint8Array
    ? Buffer.from(audioBody)
    : Buffer.from(await audioBody.arrayBuffer());
  const languageCode =
    result.headers['X-Language-Code'] ?? result.headers['x-language-code'];

  writeFileSync('speech.wav', audioBuffer);
  console.log(languageCode);
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(bearerAuth: "Bearer YOUR_API_KEY");

  var result = await sdk.Llm.Speech.SpeakAsync(new TextToSpeechRequest()
  {
      Text = "Welcome to the MKA1 API speech guide.",
      Language = TextToSpeechRequestLanguage.En,
  });

  File.WriteAllBytes("speech.wav", result.Bytes!);
  ```

  ```python Python SDK theme={null}
  result = sdk.llm.speech.speak(
      text="Welcome to the MKA1 API speech guide.",
      language="en",
  )

  with open("speech.wav", "wb") as f:
      f.write(result.body)
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/speech/tts \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "text": "Welcome to the MKA1 API speech guide.",
      "language": "en"
    }' \
    --output speech.wav
  ```
</CodeGroup>

## Transmitir fala para menor latência

Use texto para fala em streaming quando quiser que a reprodução comece antes que o arquivo de áudio completo esteja pronto.
Escolha `mp3` para cargas menores ou `pcm` para áudio não compactado.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm speech speak-streaming \
    --text 'Start speaking this response as soon as audio is ready.' \
    --language en \
    --format-param mp3 \
    --output-file speech.mp3
  ```

  ```ts MKA1 SDK theme={null}
  const result = await mka1.llm.speech.speakStreaming({
    text: 'Start speaking this response as soon as audio is ready.',
    language: 'en',
    format: 'mp3',
  }, { headers: { 'X-On-Behalf-Of': '<end-user-id>' } });

  const contentType =
    result.headers['Content-Type'] ?? result.headers['content-type'];
  const languageCode =
    result.headers['X-Language-Code'] ?? result.headers['x-language-code'];

  console.log(contentType);
  console.log(languageCode);
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(bearerAuth: "Bearer YOUR_API_KEY");

  var result = await sdk.Llm.Speech.SpeakStreamingAsync(new TextToSpeechStreamingRequest()
  {
      Text = "Start speaking this response as soon as audio is ready.",
      Language = TextToSpeechStreamingRequestLanguage.En,
      Format = TextToSpeechStreamingRequestFormat.Mp3,
  });

  // Response contains either MP3 or WAV bytes depending on format
  var audioBytes = result.TwoHundredAudioMpegBytes ?? result.TwoHundredAudioWavBytes;
  File.WriteAllBytes("speech.mp3", audioBytes!);
  ```

  ```python Python SDK theme={null}
  result = sdk.llm.speech.speak_streaming(
      text="Start speaking this response as soon as audio is ready.",
      language="en",
      format="mp3",
  )

  with open("speech.mp3", "wb") as f:
      f.write(result.body)
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/speech/tts/stream \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "text": "Start speaking this response as soon as audio is ready.",
      "language": "en",
      "format": "mp3"
    }' \
    --output speech.mp3
  ```
</CodeGroup>

## Próximos passos

* Revise a referência de [Transcrição de fala para texto](/pt/api-reference/speech/speech-to-text-transcription) para detalhes de requisição e resposta
* Revise a referência de [Texto para fala](/pt/api-reference/speech/text-to-speech) para geração de WAV
* Revise a referência de [Texto para fala em streaming](/pt/api-reference/speech/streaming-text-to-speech) para saída de baixa latência
* Use o [Modo de voz avançado](/pt/docs/advanced-voice-mode) para conversas em tempo real
