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

# Soniox

> 开始使用 Soniox 音频转录加载器（Document Loader）在 LangChain 中。

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

## 设置

安装包：

```bash npm2yarn theme={null}
npm install @soniox/langchain
```

### 凭证

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

```bash theme={null}
export SONIOX_API_KEY=your_api_key
```

## 使用

### 基本转录

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

```typescript theme={null}
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"],
    // Any other transcription parameters you find here
    // https://soniox.com/docs/stt/api-reference/transcriptions/create_transcription
  }
);

console.log(`Transcribing ${audioFileUrl}...`);
const docs = await loader.load();

const transcriptText = docs[0].pageContent;
console.log(`Transcript: ${transcriptText}`);

// Create a chain to summarize the transcript
const prompt = ChatPromptTemplate.fromTemplate(
  "Write a concise summary of the following speech:\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={null}
// Fetch the file
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); // Transcribed text
```

### 翻译

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

```typescript theme={null}
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={null}
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={null}
const loader = new SonioxAudioTranscriptLoader(
  {
    audio: audioFileUrl,
  },
  {
    enable_speaker_diarization: true,
  }
);

const docs = await loader.load();

// Access speaker information in the metadata
let currentSpeaker = null;
let output = "";
for (const token of docs[0].metadata.tokens) {
  if (currentSpeaker !== token.speaker) {
    currentSpeaker = token.speaker;
    output += `\nSpeaker ${currentSpeaker}: ${token.text.trimStart()}`;
  } else {
    output += token.text;
  }
}
console.log(output);

// Analyze the conversation
const prompt = ChatPromptTemplate.fromTemplate(
  `Analyze the following conversation between speakers.
Identify the intent of each speaker.

Conversation:
{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={null}
const loader = new SonioxAudioTranscriptLoader(
  {
    audio: audioFileUrl,
  },
  {
    enable_language_identification: true,
  }
);
```

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

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

```typescript theme={null}
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` - 高级音频编码 (Advanced Audio Coding)
* `aiff` - 音频交换文件格式 (Audio Interchange File Format)
* `amr` - 自适应多速率 (Adaptive Multi-Rate)
* `asf` - 高级系统格式 (Advanced Systems Format)
* `flac` - 自由无损音频编解码器 (Free Lossless Audio Codec)
* `mp3` - MPEG 音频层 III (MPEG Audio Layer III)
* `ogg` - Ogg Vorbis
* `wav` - 波形音频文件格式 (Waveform Audio File Format)
* `webm` - WebM 音频

### 返回值

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

```typescript theme={null}
type Document {
  pageContent: string, // The transcribed text
  metadata: SonioxTranscriptResponse // Full transcript with metadata
}
```

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

```typescript theme={null}
type SonioxTranscriptResponse = {
  id: string;
  text?: string | null;
  tokens?: SonioxTranscriptToken[] | null;
}
```

Token 类型：

```typescript theme={null}
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)

***

> 官方原文：[src/oss/javascript/integrations/document\_loaders/web\_loaders/soniox.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/javascript/integrations/document_loaders/web_loaders/soniox.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.