跳到主要内容

voice.getSpeakers()

getSpeakers() 方法从 Voice Provider 检索可用 Voice 选项(speaker)列表。应用可以向用户展示 Voice 选项,也可以根据不同情境以编程方式选择最合适的 Voice。

使用示例
使用示例的直接链接

import { OpenAIVoice } from '@mastra/voice-openai'
import { ElevenLabsVoice } from '@mastra/voice-elevenlabs'

// Initialize voice providers
const openaiVoice = new OpenAIVoice()
const elevenLabsVoice = new ElevenLabsVoice({
apiKey: process.env.ELEVENLABS_API_KEY,
})

// Get available speakers from OpenAI
const openaiSpeakers = await openaiVoice.getSpeakers()
console.log('OpenAI voices:', openaiSpeakers)
// Example output: [{ voiceId: "alloy" }, { voiceId: "echo" }, { voiceId: "fable" }, ...]

// Get available speakers from ElevenLabs
const elevenLabsSpeakers = await elevenLabsVoice.getSpeakers()
console.log('ElevenLabs voices:', elevenLabsSpeakers)
// Example output: [{ voiceId: "21m00Tcm4TlvDq8ikWAM", name: "Rachel" }, ...]

// Use a specific voice for speech
const text = 'Hello, this is a test of different voices.'
await openaiVoice.speak(text, { speaker: openaiSpeakers[2].voiceId })
await elevenLabsVoice.speak(text, { speaker: elevenLabsSpeakers[0].voiceId })

参数
参数的直接链接

此方法不接受任何参数。

返回值
返回值的直接链接

Promise<Array<{ voiceId: string } & TSpeakerMetadata>>:

Promise
一个解析为 Voice 选项数组的 Promise;每个选项至少包含 voiceId 属性,还可能包含特定于 Provider 的其他元数据。

特定于 Provider 的元数据
特定于 Provider 的元数据的直接链接

不同 Voice Provider 会为其 Voice 返回不同的元数据:

voiceId:

string
Voice 的唯一标识符(例如 'alloy'、'echo'、'fable'、'onyx'、'nova'、'shimmer')

注意事项
注意事项的直接链接

  • 不同 Provider 提供的 Voice 差异很大
  • 某些 Provider 可能需要身份验证才能检索完整的 Voice 列表
  • 如果 Provider 不支持此方法,默认实现会返回空数组
  • 如果需要频繁显示该列表,出于性能考虑,建议缓存结果
  • 所有 Provider 都保证存在 voiceId 属性,但其他元数据会有所不同