尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

如何用 AI SDK 的 transcribe 函数完成音频转写并读取分段信息

如何用 AI SDK 的 transcribe 函数完成音频转写并读取分段信息 如何用 AI SDK 的 transcribe 函数完成音频转写并读取分段信息【免费下载链接】aiThe AI Toolkit for TypeScript. From the creators of Next.js, the AI SDK is a free open-source library for building AI-powered applications and agents项目地址: https://gitcode.com/GitHub_Trending/ai/aiAI SDK 提供了transcribe函数用于调用转写模型把音频文件转成文本。本文的任务是在 Node.js 环境中用 AI SDK 的 transcribe 完成一次音频转写并从中读取带起止时间的分段信息segments。按文档说明执行需要 Node.js 22 和 pnpm以及一个可用的 OpenAI API keyOpenAI 提供商的apiKey默认读取OPENAI_API_KEY环境变量。安装依赖在一个空目录中初始化项目然后安装aiAI SDK 核心包和 OpenAI 提供商包以及运行 TypeScript 代码所需的开发依赖mkdir my-ai-app cd my-ai-app pnpm init pnpm add ai ai-sdk/openai pnpm add -D types/node tsx typescriptAPI key 通过环境变量提供在项目根目录创建.env文件并填入你的 keyOPENAI_API_KEY你的key完成一次基础转写创建index.ts用openai.transcription(whisper-1)创建转写模型音频用fs/promises的readFile读入。audio参数可以是Uint8Array、ArrayBuffer、Buffer、base64 编码的string也可以是一个URLimport { transcribe } from ai; import { openai } from ai-sdk/openai; import { readFile } from fs/promises; import dotenv/config; const transcript await transcribe({ model: openai.transcription(whisper-1), audio: await readFile(audio.mp3), }); console.log(transcript.text); // 完整转写文本文档示例Hello, world!用npx tsx index.ts运行audio.mp3替换为你自己的音频文件路径。把transcript.text打印出来并看到预期的转写文本说明转写调用已经成功。转写结果对象上还有几个属性可以按需读取const text transcript.text; // 完整转写文本 const language transcript.language; // 语言ISO-639-1 格式如 en如可用 const durationInSeconds transcript.durationInSeconds; // 时长秒如可用读取分段信息分段信息在transcript.segments上类型是Array{ text: string; startSecond: number; endSecond: number }每个元素是一段转写文本及其起止时间单位秒。OpenAI 提供商的分段时间戳由providerOptions中的timestampGranularities控制默认值就是[segment]即默认会返回分段信息基础调用不改参数也能读到segments。可选值是[word]、[segment]、[word, segment]。文档说明 segment 时间戳不增加额外延迟而生成 word 时间戳会产生额外延迟const result await transcribe({ model: openai.transcription(whisper-1), audio: await readFile(audio.mp3), providerOptions: { openai: { timestampGranularities: [segment], // 默认值[word] 可获得词级时间戳有额外延迟 }, }, }); console.log(result.segments); // Array of segments with startSecond/endSecond如果你知道音频的语种可以在providerOptions里传入languageISO-639-1 格式如en文档指出这能改善准确率和延迟providerOptions: { openai: { language: en }, },选择能返回 segments 的模型不同转写模型对segments的支持不同。OpenAI 提供商文档给出的能力矩阵是ModelTranscriptionStreamingDurationSegmentsLanguagewhisper-1支持不支持支持支持支持gpt-4o-mini-transcribe支持不支持不支持不支持不支持gpt-4o-transcribe支持不支持不支持不支持不支持gpt-4o-transcribe-diarize支持不支持支持支持不支持如果换成gpt-4o-transcribe-diarize用于区分说话人分段信息不在顶层segments上而是从providerMetadata.openai.segments读取该模型默认使用diarized_json响应格式和自动分块const result await transcribe({ model: openai.transcription(gpt-4o-transcribe-diarize), audio: new Uint8Array([1, 2, 3, 4]), }); console.log(result.providerMetadata.openai.segments);处理下载限制与错误当audio传入URL时SDK 会下载该文件默认大小上限是 2 GiB。可以用createDownload自定义上限import { transcribe, createDownload } from ai; const transcript await transcribe({ model: openai.transcription(whisper-1), audio: new URL(https://example.com/audio.mp3), download: createDownload({ maxBytes: 50 * 1024 * 1024 }), // 50 MB limit });下载超过大小时会抛出DownloadError当transcribe无法生成有效转写模型未生成响应或响应无法解析时会抛出NoTranscriptGeneratedError该错误保留responses含时间戳、模型、响应头和cause供排查import { transcribe, NoTranscriptGeneratedError, DownloadError } from ai; try { await transcribe({ model: openai.transcription(whisper-1), audio: await readFile(audio.mp3), }); } catch (error) { if (NoTranscriptGeneratedError.isInstance(error)) { console.log(NoTranscriptGeneratedError); console.log(Cause:, error.cause); console.log(Responses:, error.responses); } if (DownloadError.isInstance(error)) { console.log(Download failed:, error.message); } }另外两个可选参数abortSignalAbortSignal类型可用于取消调用或设置超时例如AbortSignal.timeout(5000)表示 5 秒后中止和headersRecordstring, string为请求附加自定义 HTTP 头。maxRetries控制最大重试次数默认 2。验证与限制成功判定运行后console.log(transcript.text)输出非空的转写文本传入timestampGranularities后console.log(result.segments)输出包含text、startSecond、endSecond字段的数组startSecond/endSecond的具体数值取决于你的音频文档未给出固定示例。转写结果上的warnings属性Warning[]会收集模型提供商返回的警告例如不支持的参数设置。language和durationInSeconds只有在模型返回时才可用类型均为可空。流式转写experimental_streamTranscribe是实验性功能适用于实时原始音频流不在本文的文件转写场景内。更多提供商ElevenLabs、Groq、Mistral、Deepgram、AssemblyAI 等支持的转写模型清单可查阅 Transcription 文档 中的 Transcription Models 表格。【免费下载链接】aiThe AI Toolkit for TypeScript. From the creators of Next.js, the AI SDK is a free open-source library for building AI-powered applications and agents项目地址: https://gitcode.com/GitHub_Trending/ai/ai创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表