mcpField
S
speech-to-text

speech-to-text

github.com/marks97创意与媒体0318 次安装4 周前更新
代码仓库

关于 speech-to-text

ElevenLabs Speech-to-Text 是一项使用 Scribe v2 转录音频的技能,适用于处理录音或实时语音的应用。它支持多语言转录、说话人标注、逐词时间戳和实时流式处理。

主要功能

  1. 01支持 90 多种语言转录
  2. 02说话人区分与角色标注
  3. 03逐词时间戳
  4. 04关键词提示
  5. 05实时流式转录

适用场景

  1. 01为长录音生成字幕
  2. 02标注会议中的说话人
  3. 03实时显示语音转写文本
  4. 04识别产品名称或技术术语

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/marks97/speech-to-text --skill speech-to-text

安装后在 Claude Code 中输入/speech-to-text确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
installation.md
realtime-client-side.md
realtime-commit-strategies.md
realtime-events.md
realtime-server-side.md
transcription-options.md

详细介绍

ElevenLabs 语音转文本

使用 Scribe v2 将音频转录为文本——支持 90 多种语言、说话人分离和单词级时间戳。

**设置:**参见安装指南。对于 JavaScript,仅使用 @elevenlabs/* 包。

API 密钥

在发起任何调用前,在环境中设置 ELEVENLABS_API_KEY(访问 https://elevenlabs.io 获取):

export ELEVENLABS_API_KEY="your-api-key"

切勿将密钥值回显到转录文本中或提交到代码库。

快速开始

Python
from elevenlabs import ElevenLabs

client = ElevenLabs()

with open("audio.mp3", "rb") as audio_file:
    result = client.speech_to_text.convert(file=audio_file, model_id="scribe_v2")

print(result.text)
JavaScript
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
import { createReadStream } from "fs";

const client = new ElevenLabsClient();
const result = await client.speechToText.convert({
  file: createReadStream("audio.mp3"),
  modelId: "scribe_v2",
});
console.log(result.text);
cURL
curl -X POST "https://api.elevenlabs.io/v1/speech-to-text" \
  -H "xi-api-key: $ELEVENLABS_API_KEY" -F "[email protected]" -F "model_id=scribe_v2"

模型

模型 ID描述最适合
scribe_v2最先进的准确度,支持 90 多种语言批量转录、字幕、长音频
scribe_v2_realtime低延迟(约 150 毫秒)实时转录、语音 Agent

带时间戳的转录

单词级时间戳包含类型分类和说话人识别:

result = client.speech_to_text.convert(
    file=audio_file, model_id="scribe_v2", timestamps_granularity="word"
)

for word in result.words:
    print(f"{word.text}: {word.start}s - {word.end}s (type: {word.type})")

说话人分离

识别谁说了什么——模型会为每个单词标注说话人 ID,适用于会议、访谈或任何多说话人音频:

result = client.speech_to_text.convert(
    file=audio_file,
    model_id="scribe_v2",
    diarize=True
)

for word in result.words:
    print(f"[{word.speaker_id}] {word.text}")

对于通话录音,批量 API 可以将分离出的说话人标记为 agent 和 customer,方法是同时设置 detect_speaker_roles=true 和 diarize=true。此选项与 use_multi_channel=true 不兼容。

curl -X POST "https://api.elevenlabs.io/v1/speech-to-text" \
  -H "xi-api-key: $ELEVENLABS_API_KEY" \
  -F "[email protected]" \
  -F "model_id=scribe_v2" \
  -F "diarize=true" \
  -F "detect_speaker_roles=true"

关键词提示

帮助模型识别可能听错的特定词语,例如产品名称、技术术语或特殊拼写(最多 100 个词语):

result = client.speech_to_text.convert(
    file=audio_file,
    model_id="scribe_v2",
    keyterms=["ElevenLabs", "Scribe", "API"]
)

语言检测

自动检测,可选语言提示:

result = client.speech_to_text.convert(
    file=audio_file,
    model_id="scribe_v2",
    language_code="eng"  # ISO 639-1 or ISO 639-3 code
)

print(f"Detected: {result.language_code} ({result.language_probability:.0%})")

支持的格式

**音频:**MP3、WAV、M4A、FLAC、OGG、WebM、AAC、AIFF、Opus **视频:**MP4、AVI、MKV、MOV、WMV、FLV、WebM、MPEG、3GPP

**限制:**文件大小最多 3GB,时长最多 10 小时

响应格式

{
  "text": "The full transcription text",
  "language_code": "eng",
  "language_probability": 0.98,
  "words": [
    {"text": "The", "start": 0.0, "end": 0.15, "type": "word", "speaker_id": "speaker_0"},
    {"text": " ", "start": 0.15, "end": 0.16, "type": "spacing", "speaker_id": "speaker_0"}
  ]
}

单词类型:

  • word - 实际说出的单词
  • spacing - 单词之间的空白(便于精确计时)
  • audio_event - 模型检测到的非语音声音(笑声、掌声、音乐等)

错误处理

try:
    result = client.speech_to_text.convert(file=audio_file, model_id="scribe_v2")
except Exception as e:
    print(f"Transcription failed: {e}")

常见错误:

  • 401:API 密钥无效
  • 422:参数无效
  • 429:超出速率限制

跟踪成本

通过 request-id 响应标头监控用量:

response = client.speech_to_text.convert.with_raw_response(file=audio_file, model_id="scribe_v2")
result = response.parse()
print(f"Request ID: {response.headers.get('request-id')}")

实时流式处理

如需以超低延迟(约 150 毫秒)进行实时转录,请使用实时 API。实时 API 会生成两种转录文本:

  • **部分转录文本:**随着音频处理而频繁更新的临时结果——可用于实时反馈(例如,在用户说话时显示文本)
  • 已提交转录文本:“提交”后生成的最终稳定结果——可将其作为应用的真实数据来源

“提交”会指示模型完成当前片段。你可以手动提交(例如,在用户暂停时),也可以使用语音活动检测(VAD)在静音时自动提交。

Python(服务端)
import asyncio
from elevenlabs import ElevenLabs

client = ElevenLabs()

async def transcribe_realtime():
    async with client.speech_to_text.realtime.connect(
        model_id="scribe_v2_realtime",
        include_timestamps=True,
    ) as connection:
        await connection.stream_url("https://example.com/audio.mp3")

        async for event in connection:
            if event.type == "partial_transcript":
                print(f"Partial: {event.text}")
            elif event.type == "committed_transcript":
                print(f"Final: {event.text}")

asyncio.run(transcribe_realtime())
JavaScript(使用 React 的客户端)
import { useScribe, CommitStrategy } from "@elevenlabs/react";

function TranscriptionComponent() {
  const [transcript, setTranscript] = useState("");

  const scribe = useScribe({
    modelId: "scribe_v2_realtime",
    commitStrategy: CommitStrategy.VAD, // Auto-commit on silence for mic input
    onPartialTranscript: (data) => console.log("Partial:", data.text),
    onCommittedTranscript: (data) => setTranscript((prev) => prev + data.text),
  });

  const start = async () => {
    // Get token from your backend (never expose API key to client)
    const { token } = await fetch("/scribe-token").then((r) => r.json());

    await scribe.connect({
      token,
      microphone: { echoCancellation: true, noiseSuppression: true },
    });
  };

  return <button onClick={start}>Start Recording</button>;
}
提交策略
策略描述
手动准备就绪时调用 commit()——适用于文件处理或由你控制音频片段的情况
VAD语音活动检测会在检测到静音时自动提交——适用于实时麦克风输入
// React: set commitStrategy on the hook (recommended for mic input)
import { useScribe, CommitStrategy } from "@elevenlabs/react";

const scribe = useScribe({
  modelId: "scribe_v2_realtime",
  commitStrategy: CommitStrategy.VAD,
  // Optional VAD tuning:
  vadSilenceThresholdSecs: 1.5,
  vadThreshold: 0.4,
});
// JavaScript client: pass vad config on connect
const connection = await client.speechToText.realtime.connect({
  modelId: "scribe_v2_realtime",
  vad: {
    silenceThresholdSecs: 1.5,
    threshold: 0.4,
  },
});
事件类型
事件描述
partial_transcript实时临时结果
committed_transcript提交后的最终结果
committed_transcript_with_timestamps带单词时间信息的最终结果
error发生错误

完整文档请参见实时参考资料。

参考资料

评论

支持 Markdown