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

# SDK JavaScript

> **Info**
>
> Per una panoramica di Scribe e delle sue funzionalità, consulta la [panoramica di Speech to Text ](/docs/it/capabilities/speech-to-text). Per guide dettagliate sull'utilizzo, consulta lo [streaming lato client](/docs/it/eleven-api/guides/how-to/speech-to-text/realtime/client-side-streaming).

## Installazione

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

> **Tip**
>
> Usa la [skill Speech to Text di ElevenLabs](https://github.com/elevenlabs/skills/tree/main/speech-to-text) per trascrivere l'audio dal tuo assistente di programmazione IA:
>
> ```bash
> npx skills add elevenlabs/skills --skill speech-to-text
> ```

> **Note**
>
> Questa libreria può essere utilizzata in qualsiasi progetto basato su JavaScript. Se usi React, considera l'
> [hook `useScribe`](/docs/it/eleven-api/resources/libraries/scribe-stt/react-scribe), che offre
> la gestione integrata dello stato e del ciclo di vita.

## Utilizzo

Ecco un esempio minimo funzionante che si connette a Scribe e registra i risultati della trascrizione:

```js
import { Scribe, RealtimeEvents } from "@elevenlabs/client";

const token = await fetchTokenFromServer();

const connection = Scribe.connect({
  token,
  modelId: "scribe_v2_realtime",
  microphone: {
    echoCancellation: true,
    noiseSuppression: true,
  },
});

connection.on(RealtimeEvents.PARTIAL_TRANSCRIPT, (data) => {
  console.log("Partial:", data.text);
});

connection.on(RealtimeEvents.COMMITTED_TRANSCRIPT, (data) => {
  console.log("Committed:", data.text);
});

// Later, close the connection
connection.close();
```

## Ottenere un token

Scribe richiede un token monouso per l'autenticazione. Crea un endpoint API sul tuo server:

```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**
>
> La tua chiave API ElevenLabs è sensibile. Non esporla mai al client. Genera sempre il token sul
> server.

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

## Opzioni di connessione

`Scribe.connect()` accetta opzioni per il microfono o opzioni audio manuali. Entrambe condividono un insieme comune di opzioni di base.

### Opzioni di base

| Proprietà                   | Tipo             | Predefinito                 | Descrizione                                                                                   |
| --------------------------- | ---------------- | --------------------------- | --------------------------------------------------------------------------------------------- |
| **token**                   | `string`         |                             | Token monouso per l'autenticazione WebSocket.                                                 |
| **modelId**                 | `string`         |                             | ID del modello (ad es. `"scribe_v2_realtime"`).                                               |
| **baseUri**                 | `string`         | `"wss://api.elevenlabs.io"` | URI di base WebSocket personalizzato.                                                         |
| **commitStrategy**          | `CommitStrategy` | `"manual"`                  | `"manual"` o `"vad"`.                                                                         |
| **vadSilenceThresholdSecs** | `number`         | `1.5`                       | Secondi di silenzio prima che VAD esegua il commit (0.3-3.0).                                 |
| **vadThreshold**            | `number`         | `0.4`                       | Sensibilità VAD (0.1-0.9, valori più bassi sono più sensibili).                               |
| **minSpeechDurationMs**     | `number`         | `100`                       | Durata minima del parlato in ms (50-2000).                                                    |
| **minSilenceDurationMs**    | `number`         | `100`                       | Durata minima del silenzio in ms (50-2000).                                                   |
| **languageCode**            | `string`         |                             | Codice lingua ISO-639-1 o ISO-639-3. Lascia vuoto per il rilevamento automatico.              |
| **includeTimestamps**       | `boolean`        | `false`                     | Ricevi timestamp a livello di parola tramite l'evento `COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS`. |

### Opzioni del microfono

Passa un oggetto `microphone` per trasmettere l'audio direttamente dal microfono dell'utente. La connessione gestisce automaticamente `getUserMedia` e la codifica audio.

```js
const connection = Scribe.connect({
  token,
  modelId: "scribe_v2_realtime",
  microphone: {
    deviceId: "optional-device-id",
    echoCancellation: true,
    noiseSuppression: true,
    autoGainControl: true,
  },
});
```

| Proprietà            | Tipo      | Descrizione                                   |
| -------------------- | --------- | --------------------------------------------- |
| **deviceId**         | `string`  | ID di uno specifico dispositivo microfono.    |
| **echoCancellation** | `boolean` | Abilita la cancellazione dell'eco.            |
| **noiseSuppression** | `boolean` | Abilita la soppressione del rumore.           |
| **autoGainControl**  | `boolean` | Abilita il controllo automatico del guadagno. |

### Opzioni audio manuali

Passa `audioFormat` e `sampleRate` per inviare manualmente dati audio tramite `connection.send()`.

```js
import { AudioFormat } from "@elevenlabs/client";

const connection = Scribe.connect({
  token,
  modelId: "scribe_v2_realtime",
  audioFormat: AudioFormat.PCM_16000,
  sampleRate: 16000,
});
```

| Proprietà       | Tipo          | Descrizione                                                           |
| --------------- | ------------- | --------------------------------------------------------------------- |
| **audioFormat** | `AudioFormat` | Formato di codifica audio (ad es. `AudioFormat.PCM_16000`).           |
| **sampleRate**  | `number`      | Frequenza di campionamento in Hz. Deve corrispondere a `audioFormat`. |

#### Enum AudioFormat

```typescript
enum AudioFormat {
  PCM_8000 = "pcm_8000",
  PCM_16000 = "pcm_16000",
  PCM_22050 = "pcm_22050",
  PCM_24000 = "pcm_24000",
  PCM_44100 = "pcm_44100",
  PCM_48000 = "pcm_48000",
  ULAW_8000 = "ulaw_8000",
}
```

## Modalità microfono

Trasmetti l'audio direttamente dal microfono dell'utente:

```js
import { Scribe, RealtimeEvents } from "@elevenlabs/client";

async function transcribeFromMicrophone() {
  const token = await fetchToken();

  const connection = Scribe.connect({
    token,
    modelId: "scribe_v2_realtime",
    microphone: {
      echoCancellation: true,
      noiseSuppression: true,
      autoGainControl: true,
    },
  });

  connection.on(RealtimeEvents.PARTIAL_TRANSCRIPT, (data) => {
    document.getElementById("live").textContent = data.text;
  });

  connection.on(RealtimeEvents.COMMITTED_TRANSCRIPT, (data) => {
    const el = document.createElement("p");
    el.textContent = data.text;
    document.getElementById("transcripts").appendChild(el);
    document.getElementById("live").textContent = "";
  });

  document.getElementById("stop").addEventListener("click", () => {
    connection.close();
  });
}
```

## Modalità audio manuale (trascrizione di file)

Trascrivi file audio preregistrati inviando manualmente dati audio:

```js
import { Scribe, RealtimeEvents, AudioFormat } from "@elevenlabs/client";

async function transcribeFile(file) {
  const token = await fetchToken();

  const connection = Scribe.connect({
    token,
    modelId: "scribe_v2_realtime",
    audioFormat: AudioFormat.PCM_16000,
    sampleRate: 16000,
  });

  connection.on(RealtimeEvents.COMMITTED_TRANSCRIPT, (data) => {
    console.log("Transcript:", data.text);
  });

  // 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));

    connection.send({ audioBase64: base64 });
    await new Promise((resolve) => setTimeout(resolve, 50));
  }

  // Commit and close
  connection.commit();
}
```

## RealtimeConnection

`Scribe.connect()` restituisce un'istanza di `RealtimeConnection` con i seguenti metodi.

### on(event, listener)

Registra un listener di eventi. Consulta [Eventi](#events) per i tipi di evento disponibili.

```js
connection.on(RealtimeEvents.COMMITTED_TRANSCRIPT, (data) => {
  console.log("Committed:", data.text);
});
```

### off(event, listener)

Rimuovi un listener di eventi registrato in precedenza.

```js
const handler = (data) => console.log(data.text);
connection.on(RealtimeEvents.COMMITTED_TRANSCRIPT, handler);

// Later
connection.off(RealtimeEvents.COMMITTED_TRANSCRIPT, handler);
```

### send(data)

Invia dati audio a Scribe (solo modalità audio manuale).

```js
connection.send({
  audioBase64: base64AudioChunk,
  commit: false, // Optional: commit immediately
  sampleRate: 16000, // Optional: override sample rate
  previousText: "Previous transcription text", // Optional: context from a previous transcription
});
```

> **Warning**
>
> Il campo `previousText` può essere inviato solo nel primo chunk audio di una sessione. Se lo invii nei
> chunk successivi, si verifica un errore.

### commit()

Esegui manualmente il commit della trascrizione corrente. Necessario solo quando usi `CommitStrategy.MANUAL`.

```js
connection.commit();
```

### close()

Chiudi la connessione WebSocket e libera le risorse (stream del microfono, contesto audio).

```js
connection.close();
```

## Eventi

Registra listener di eventi con `connection.on(event, listener)`. Tutti gli eventi sono disponibili come costanti nell'enum `RealtimeEvents`.

### Eventi di trascrizione

| Evento                                      | Dati                                                            | Descrizione                                                    |
| ------------------------------------------- | --------------------------------------------------------------- | -------------------------------------------------------------- |
| **SESSION\_STARTED**                        | `{ session_id: string }`                                        | Sessione Scribe avviata.                                       |
| **PARTIAL\_TRANSCRIPT**                     | `{ text: string }`                                              | Risultato della trascrizione provvisorio.                      |
| **COMMITTED\_TRANSCRIPT**                   | `{ text: string }`                                              | Risultato della trascrizione finalizzato.                      |
| **COMMITTED\_TRANSCRIPT\_WITH\_TIMESTAMPS** | `{ text: string; language_code?: string; words?: WordsItem[] }` | Risultato finalizzato con temporizzazione a livello di parola. |

Il tipo `WordsItem` contiene informazioni sulla temporizzazione a livello di parola:

```typescript
interface WordsItem {
  text?: string; // Word text
  start?: number; // Start time in seconds
  end?: number; // End time in seconds
  type?: "word" | "spacing"; // Token type
  speaker_id?: string; // Speaker identifier
}
```

### Eventi di connessione

| Evento    | Dati             | Descrizione                   |
| --------- | ---------------- | ----------------------------- |
| **OPEN**  | `Event`          | Connessione WebSocket aperta. |
| **CLOSE** | `Event`          | Connessione WebSocket chiusa. |
| **ERROR** | `Error \| Event` | Errore generico.              |

### Eventi di errore

Tutti gli eventi di errore ricevono `{ error: string }`.

| Evento                             | Descrizione                                                |
| ---------------------------------- | ---------------------------------------------------------- |
| **AUTH\_ERROR**                    | Errore di autenticazione.                                  |
| **QUOTA\_EXCEEDED**                | Quota di utilizzo superata.                                |
| **COMMIT\_THROTTLED**              | Richiesta di commit limitata.                              |
| **TRANSCRIBER\_ERROR**             | Errore del motore di trascrizione.                         |
| **UNACCEPTED\_TERMS**              | Termini di servizio non accettati.                         |
| **RATE\_LIMITED**                  | Limite di frequenza raggiunto.                             |
| **INPUT\_ERROR**                   | Formato di input non valido.                               |
| **QUEUE\_OVERFLOW**                | Coda di elaborazione piena.                                |
| **RESOURCE\_EXHAUSTED**            | Risorse del server al limite della capacità.               |
| **SESSION\_TIME\_LIMIT\_EXCEEDED** | Tempo massimo della sessione raggiunto.                    |
| **CHUNK\_SIZE\_EXCEEDED**          | Chunk audio troppo grande.                                 |
| **INSUFFICIENT\_AUDIO\_ACTIVITY**  | Attività audio insufficiente per mantenere la connessione. |

## Strategie di commit

Controlla quando vengono eseguiti i commit delle trascrizioni:

```js
import { Scribe, CommitStrategy } from '@elevenlabs/client';

// Manual (default): you control when to commit
const connection = Scribe.connect({
  token,
  modelId: 'scribe_v2_realtime',
  audioFormat: AudioFormat.PCM_16000,
  sampleRate: 16000,
  commitStrategy: CommitStrategy.MANUAL,
});

// Send audio, then commit when ready
connection.send({ audioBase64: chunk });
connection.commit();

// Voice Activity Detection: Scribe detects silences and commits automatically
const connection = Scribe.connect({
  token,
  modelId: 'scribe_v2_realtime',
  microphone: { echoCancellation: true },
  commitStrategy: CommitStrategy.VAD,
});
```

Per maggiori dettagli, consulta [Trascrizioni e strategie di commit](/docs/it/eleven-api/guides/how-to/speech-to-text/realtime/transcripts-and-commit-strategies).

## Esempio completo

Ecco un esempio completo che trascrive l'audio del microfono con una strategia di commit basata su VAD:

```js
import { Scribe, RealtimeEvents, CommitStrategy } from "@elevenlabs/client";

async function startTranscription() {
  const token = await fetchToken();

  const connection = Scribe.connect({
    token,
    modelId: "scribe_v2_realtime",
    commitStrategy: CommitStrategy.VAD,
    microphone: {
      echoCancellation: true,
      noiseSuppression: true,
    },
  });

  connection.on(RealtimeEvents.SESSION_STARTED, (data) => {
    console.log("Session started:", data.session_id);
  });

  connection.on(RealtimeEvents.PARTIAL_TRANSCRIPT, (data) => {
    document.getElementById("live").textContent = data.text;
  });

  connection.on(RealtimeEvents.COMMITTED_TRANSCRIPT, (data) => {
    const el = document.createElement("p");
    el.textContent = data.text;
    document.getElementById("transcripts").appendChild(el);
    document.getElementById("live").textContent = "";
  });

  connection.on(RealtimeEvents.ERROR, (error) => {
    console.error("Scribe error:", error);
  });

  // Stop button
  document.getElementById("stop").addEventListener("click", () => {
    connection.close();
  });
}

document.getElementById("start").addEventListener("click", startTranscription);
```