> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Soniox

开始使用 LangChain 中的 [Soniox](https://soniox.com/) 音频转录加载器。

## 设置

安装包：

```bash npm2yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
npm install @soniox/langchain
```

### 凭证

从 [Soniox 控制台](https://console.soniox.com) 获取您的 Soniox API 密钥，并将其设置为环境变量：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export SONIOX_API_KEY=your_api_key
```

## 使用

### 基础转录

示例如何使用 `SonioxAudioTranscriptLoader` 转录音频文件，并使用 LLM 生成摘要。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { SonioxAudioTranscriptLoader } from "@soniox/langchain";
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";

const audioFileUrl = "https://soniox.com/media/examples/coffee_shop.mp3";
const loader = new SonioxAudioTranscriptLoader(
  {
    audio: audioFileUrl,
  },
  {
    language_hints: ["en"],
    // 您可以在此处找到的任何其他转录参数
    // https://soniox.com/docs/stt/api-reference/transcriptions/create_transcription
  }
);

console.log(`正在转录 ${audioFileUrl}...`);
const docs = await loader.load();

const transcriptText = docs[0].pageContent;
console.log(`转录文本：${transcriptText}`);

// 创建用于总结转录文本的链
const prompt = ChatPromptTemplate.fromTemplate(
  "为以下语音写一个简洁的摘要：\n\n{transcript}"
);

const chain = prompt
  .pipe(new ChatOpenAI({ model: "gpt-5-mini" }))
  .pipe(new StringOutputParser());

const summary = await chain.invoke({ transcript: transcriptText });
console.log(summary);
```

您也可以从二进制数据转录音频：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
// 获取文件
const response = await fetch("https://github.com/soniox/soniox_examples/raw/refs/heads/master/speech_to_text/assets/coffee_shop.mp3");
const audioBuffer = await response.bytes(); // Uint8Array

const loader = new SonioxAudioTranscriptLoader({
    audio: audioBuffer,
})

const docs = await loader.load();
console.log(docs[0].pageContent); // 转录文本
```

### 翻译

将任何检测到的语言翻译为目标语言：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const loader = new SonioxAudioTranscriptLoader(
  {
    audio: audioFileUrl,
  },
  {
    translation: {
      type: "one_way",
      target_language: "fr",
    },
    language_hints: ["en"],
  }
);

const docs = await loader.load();

let originalText = "";
let translatedText = "";

for (const token of docs[0].metadata.tokens) {
  if (token.translation_status === "translation") {
    translatedText += token.text;
  } else {
    originalText += token.text;
  }
}

console.log(originalText);
console.log(translatedText);
```

您也可以使用 `two_way` 翻译类型同时进行转录和两种语言之间的翻译。了解更多关于 [Soniox 翻译](https://soniox.com/docs/stt/async/async-translation) 的信息。

### 语言提示

Soniox 自动检测并转录 [**60 多种语言**](https://soniox.com/docs/stt/concepts/supported-languages) 的语音。当您知道音频中可能出现哪些语言时，提供 `language_hints` 可以通过偏向识别这些语言来提高准确性。

语言提示 **不限制** 识别——它们仅 **偏向** 模型朝向指定的语言，同时仍允许检测其他语言（如果存在）。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const loader = new SonioxAudioTranscriptLoader(
  {
    audio: audioFileUrl,
  },
  {
    language_hints: ["en", "es"],
  }
);

const docs = await loader.load();
```

更多详情，请参阅 [Soniox 语言提示文档](https://soniox.com/docs/stt/concepts/language-hints)。

### 说话人分离

启用说话人识别以区分不同的说话人：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const loader = new SonioxAudioTranscriptLoader(
  {
    audio: audioFileUrl,
  },
  {
    enable_speaker_diarization: true,
  }
);

const docs = await loader.load();

// 在元数据中访问说话人信息
let currentSpeaker = null;
let output = "";
for (const token of docs[0].metadata.tokens) {
  if (currentSpeaker !== token.speaker) {
    currentSpeaker = token.speaker;
    output += `\n说话人 ${currentSpeaker}：${token.text.trimStart()}`;
  } else {
    output += token.text;
  }
}
console.log(output);

// 分析对话
const prompt = ChatPromptTemplate.fromTemplate(
  `分析以下说话人之间的对话。
识别每个说话人的意图。

对话：
{conversation}`
);

const chain = prompt
  .pipe(new ChatOpenAI({ model: "gpt-5-mini" }))
  .pipe(new StringOutputParser());

const analysis = await chain.invoke({ conversation: output });
console.log(analysis);
```

### 语言识别

启用自动语言检测和识别：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const loader = new SonioxAudioTranscriptLoader(
  {
    audio: audioFileUrl,
  },
  {
    enable_language_identification: true,
  }
);
```

### 上下文以提高准确性

提供特定领域的 [上下文](https://soniox.com/docs/stt/concepts/context) 以提高转录准确性：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const loader = new SonioxAudioTranscriptLoader(
  {
    audio: audioBuffer,
  },
  {
    context: {
      general: [
        { key: "industry", value: "healthcare" },
        { key: "meeting_type", value: "consultation" }
      ],
      terms: ["hypertension", "cardiology", "metformin"],
      translation_terms: [
        { source: "blood pressure", target: "presión arterial" },
        { source: "medication", target: "medicamento" }
      ]
    }
  }
);
```

更多详情，请参阅 [Soniox 上下文文档](https://soniox.com/docs/stt/concepts/context)。

## API 参考

### 构造函数参数

#### SonioxLoaderParams（必需）

| 参数                  | 类型                     | 必需 | 描述                                          |
| ------------------- | ---------------------- | -- | ------------------------------------------- |
| `audio`             | `Uint8Array \| string` | 是  | 音频文件作为缓冲区或 URL                              |
| `audioFormat`       | `SonioxAudioFormat`    | 否  | 音频文件格式                                      |
| `apiKey`            | `string`               | 否  | Soniox API 密钥（默认为 `SONIOX_API_KEY` 环境变量）    |
| `apiBaseUrl`        | `string`               | 否  | API 基础 URL（默认为 `https://api.soniox.com/v1`） |
| `pollingIntervalMs` | `number`               | 否  | 轮询间隔（毫秒）（最小值：1000，默认值：1000）                 |
| `pollingTimeoutMs`  | `number`               | 否  | 轮询超时（毫秒）（默认值：180000）                        |

#### SonioxLoaderOptions（可选）

| 参数                               | 类型                           | 描述                         |
| -------------------------------- | ---------------------------- | -------------------------- |
| `model`                          | `SonioxTranscriptionModelId` | 使用的模型（默认：`"stt-async-v4"`） |
| `translation`                    | `object`                     | 翻译配置                       |
| `language_hints`                 | `string[]`                   | 转录的语言提示                    |
| `language_hints_strict`          | `boolean`                    | 强制执行严格的语言提示                |
| `enable_speaker_diarization`     | `boolean`                    | 启用说话人识别                    |
| `enable_language_identification` | `boolean`                    | 启用语言检测                     |
| `context`                        | `object`                     | 用于提高准确性的上下文                |

浏览 [文档](https://soniox.com/docs/stt/api-reference/transcriptions/create_transcription) 以获取支持的完整选项列表。

### 支持的音频格式

* `aac` - 高级音频编码
* `aiff` - 音频交换文件格式
* `amr` - 自适应多速率
* `asf` - 高级系统格式
* `flac` - 免费无损音频编解码器
* `mp3` - MPEG 音频层 III
* `ogg` - Ogg Vorbis
* `wav` - 波形音频文件格式
* `webm` - WebM 音频

### 返回值

`load()` 方法返回一个包含单个 `Document` 对象的数组：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
type Document {
  pageContent: string, // 转录文本
  metadata: SonioxTranscriptResponse // 包含元数据的完整转录
}
```

元数据包括转录文本、说话人信息（如果启用了分离）、语言信息（如果启用了识别）、翻译数据（如果启用了翻译）以及时间信息。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
type SonioxTranscriptResponse = {
  id: string;
  text?: string | null;
  tokens?: SonioxTranscriptToken[] | null;
}
```

令牌类型：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
type SonioxTranscriptToken = {
  text: string;
  start_ms?: number | null;
  end_ms?: number | null;
  confidence?: number | null;
  speaker?: number | string | null;
  language?: string | null;
  translation_status?: string | null;
};
```

您可以在 [Soniox REST API 参考](https://soniox.com/docs/stt/api-reference/transcriptions/get_transcription_transcript) 中了解更多关于 `SonioxTranscriptResponse` 类型的信息。

## 相关

* [Soniox API 文档](https://soniox.com/docs)

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\javascript\integrations\document_loaders\web_loaders\soniox.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
