mcpField
S
speech-to-text

speech-to-text

github.com/connorads创意与媒体1863 次安装1 天前更新
代码仓库

关于 speech-to-text

这是面向开发者和团队的 ElevenLabs 语音转文字技能,可转写录音或实时音频。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/connorads/dotfiles --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/* 软件包。

快速开始

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低延迟(约 150ms)实时转录、语音 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 中同时设置 detect_speaker_roles=true 和 diarize=true,将分离出的说话人标记为 agent 和 customer。此选项与 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')}")

实时流式传输

如需以超低延迟(约 150ms)进行实时转录,请使用实时 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