语音转文本(STT)
Mastra 中的语音转文本(STT)为通过多个服务 Provider 将音频输入转换为文本提供了标准化接口。 STT 让支持语音的应用能够响应人类语音。它支持免手持交互,改善残障用户的无障碍体验,也提供了更自然的交互界面。
配置配置的直接链接
要在 Mastra 中使用 STT,需要在初始化语音 Provider 时提供 listeningModel。其中包括以下参数:
name:要使用的具体 STT 模型。apiKey:用于身份验证的 API 密钥。- Provider 特定选项:特定语音 Provider 可能要求或支持的其他选项。
行为:所有这些参数都是可选的。你可以使用语音 Provider 提供的默认设置,具体设置取决于所用 Provider。
const voice = new OpenAIVoice({
listeningModel: {
name: 'whisper-1',
apiKey: process.env.OPENAI_API_KEY,
},
})
// If using default settings the configuration can be simplified to:
const voice = new OpenAIVoice()
可用 Provider可用 Provider的直接链接
Mastra 支持多个语音转文本 Provider,每个 Provider 都有各自的能力和优势:
- OpenAI:使用 Whisper 模型提供高准确度转录
- Azure:Microsoft 的语音识别服务,具备企业级可靠性
- ElevenLabs:支持多种语言的高级语音识别
- Google:Google 的语音识别服务,提供广泛的语言支持
- Cloudflare:针对低延迟应用进行边缘优化的语音识别
- Deepgram:AI 驱动的语音识别,可高准确度识别多种口音
- Sarvam:专注于印度语言和口音
每个 Provider 都作为独立软件包实现,可按需安装:
pnpm add @mastra/voice-openai@latest # Example for OpenAI
使用 listen 方法使用 listen 方法的直接链接
STT 的主要方法是 listen(),它会将语音音频转换为文本。用法如下:
import { Agent } from '@mastra/core/agent'
import { OpenAIVoice } from '@mastra/voice-openai'
import { getMicrophoneStream } from '@mastra/node-audio'
const voice = new OpenAIVoice()
const agent = new Agent({
id: 'voice-agent',
name: 'Voice Agent',
instructions: 'You are a voice assistant that provides recommendations based on user input.',
model: 'openai/gpt-5.6-sol',
voice,
})
const audioStream = getMicrophoneStream() // Assume this function gets audio input
const transcript = await agent.voice.listen(audioStream, {
filetype: 'm4a', // Optional: specify the audio file type
})
console.log(`User said: ${transcript}`)
const { text } = await agent.generate(
`Based on what the user said, provide them a recommendation: ${transcript}`,
)
console.log(`Recommendation: ${text}`)
转录音频文件转录音频文件的直接链接
listen() 方法接受来自麦克风或文件的音频数据流。需要转录音频文件时,请使用 createReadStream():
import { createReadStream } from 'fs'
import path from 'path'
const audioFilePath = path.join(process.cwd(), 'agent.m4a')
const audioStream = createReadStream(audioFilePath)
const transcription = await agent.voice.listen(audioStream, {
filetype: 'm4a',
})
console.log(`Transcription: ${transcription}`)
有关 Agent 上语音 Provider 的更全面概览,请参阅 Mastra 中的 Voice。