文本转语音(TTS)
Mastra 中的文本转语音(TTS)提供统一 API,可使用不同 Provider 将文本合成为语音音频。 在应用中加入 TTS,可以通过自然的语音交互提升用户体验,改善视障用户的无障碍体验,并创建更具吸引力的多模态界面。
TTS 是所有语音应用的核心组件。它与 STT(语音转文本)结合,构成语音交互系统的基础。较新的模型支持 STS(语音转语音),可用于实时交互,但费用较高($)。
配置配置的直接链接
要在 Mastra 中使用 TTS,需要在初始化语音 Provider 时提供 speechModel。其中包括以下参数:
name:要使用的具体 TTS 模型。apiKey:用于身份验证的 API 密钥。- Provider 特定选项:特定语音 Provider 可能要求或支持的其他选项。
speaker 选项可用于选择不同的语音进行语音合成。每个 Provider 都提供具有不同语音多样性、质量、语音个性和多语言支持特征的语音选项。
行为:所有这些参数都是可选的。你可以使用语音 Provider 提供的默认设置,具体设置取决于所用 Provider。
const voice = new OpenAIVoice({
speechModel: {
name: 'tts-1-hd',
apiKey: process.env.OPENAI_API_KEY,
},
speaker: 'alloy',
})
// If using default settings the configuration can be simplified to:
const voice = new OpenAIVoice()
可用 Provider可用 Provider的直接链接
Mastra 支持多个文本转语音 Provider,每个 Provider 都有独特的能力和语音选项。你可以选择最适合应用需求的 Provider:
- OpenAI:提供具有自然语调和表达力的高质量语音
- Azure:Microsoft 的语音服务,支持多种语音和语言
- ElevenLabs:提供带有情感和精细控制能力的超逼真语音
- PlayAI:专注于多种风格的自然语音
- Google:Google 的语音合成服务,支持多种语言
- Cloudflare:针对低延迟应用进行边缘优化的语音合成
- Deepgram:高准确度的 AI 驱动语音技术
- Speechify:针对可读性和无障碍体验优化的文本转语音
- Sarvam:专注于印度语言和口音
- Murf:具有可自定义参数的录音室级配音
每个 Provider 都作为独立软件包实现,可按需安装:
pnpm add @mastra/voice-openai@latest # Example for OpenAI
使用 speak 方法使用 speak 方法的直接链接
TTS 的主要方法是 speak(),它会将文本转换为语音。此方法接受选项,可用于指定 speaker 和其他 Provider 特定选项。用法如下:
import { Agent } from '@mastra/core/agent'
import { OpenAIVoice } from '@mastra/voice-openai'
const voice = new OpenAIVoice()
const agent = new Agent({
id: 'voice-agent',
name: 'Voice Agent',
instructions: 'You are a voice assistant that can help users with their tasks.',
model: 'openai/gpt-5.6-sol',
voice,
})
const { text } = await agent.generate('What color is the sky?')
// Convert text to speech to an Audio Stream
const readableStream = await voice.speak(text, {
speaker: 'default', // Optional: specify a speaker
properties: {
speed: 1.0, // Optional: adjust speech speed
pitch: 'default', // Optional: specify pitch if supported
},
})
保存语音输出保存语音输出的直接链接
speak() 方法返回音频流。需要保存生成的语音供以后播放或处理时,可将该流通过管道写入文件:
import { createWriteStream } from 'fs'
import path from 'path'
const audio = await agent.voice.speak('Hello, world!')
const filePath = path.join(process.cwd(), 'agent.mp3')
const writer = createWriteStream(filePath)
audio.pipe(writer)
await new Promise<void>((resolve, reject) => {
writer.on('finish', () => resolve())
writer.on('error', reject)
})
有关 Agent 上语音 Provider 的更全面概览,请参阅 Mastra 中的 Voice。