CompositeVoice
CompositeVoice class 可讓你組合不同的語音 Provider,以執行文字轉語音和語音轉文字操作。當你想為每項操作選用最合適的 Provider 時,此功能尤其實用,例如使用 OpenAI 將語音轉換成文字,並使用 PlayAI 將文字轉換成語音。
CompositeVoice 同時支援 Mastra 語音 Provider 和 AI SDK 模型 Provider。
建構函式參數建構函式參數 的直接連結
config:
object
複合語音服務的設定物件
config.input?:
MastraVoice | TranscriptionModel
用於語音轉文字操作的語音 Provider 或 AI SDK 轉錄模型。AI SDK 模型會自動被包裝。
config.output?:
MastraVoice | SpeechModel
用於文字轉語音操作的語音 Provider 或 AI SDK 語音模型。AI SDK 模型會自動被包裝。
config.realtime?:
MastraVoice
用於即時語音轉語音操作的語音 Provider
方法方法 的直接連結
speak()speak 的直接連結
使用已設定的說話 Provider 將文字轉換成語音。
input:
string | NodeJS.ReadableStream
要轉換成語音的文字
options?:
object
傳遞給說話 Provider 的 Provider 專用選項
注意事項:
- 如未設定說話 Provider,此方法會拋出錯誤
- 選項會直接傳遞給已設定的說話 Provider
- 傳回音訊資料串流
listen()listen 的直接連結
使用已設定的聆聽 Provider 將語音轉換成文字。
audioStream:
NodeJS.ReadableStream
要轉換成文字的音訊串流
options?:
object
傳遞給聆聽 Provider 的 Provider 專用選項
注意事項:
- 如未設定聆聽 Provider,此方法會拋出錯誤
- 選項會直接傳遞給已設定的聆聽 Provider
- 視乎 Provider 而定,傳回字串或轉錄文字串流
getSpeakers()getspeakers 的直接連結
傳回說話 Provider 提供的可用語音清單,其中每個節點包含:
voiceId:
string
語音的唯一識別碼
key?:
value
因 Provider 而異的其他語音屬性(例如名稱、語言)
注意事項:
- 只傳回說話 Provider 的語音
- 如未設定說話 Provider,則傳回空陣列
- 每個語音物件至少會有 voiceId 屬性
- 其他語音屬性取決於說話 Provider
使用範例使用範例 的直接連結
使用 Mastra 語音 Provider使用 Mastra 語音 Provider 的直接連結
import { CompositeVoice } from '@mastra/core/voice'
import { OpenAIVoice } from '@mastra/voice-openai'
import { PlayAIVoice } from '@mastra/voice-playai'
// Create voice providers
const openai = new OpenAIVoice()
const playai = new PlayAIVoice()
// Use OpenAI for listening (speech-to-text) and PlayAI for speaking (text-to-speech)
const voice = new CompositeVoice({
input: openai,
output: playai,
})
// Convert speech to text using OpenAI
const text = await voice.listen(audioStream)
// Convert text to speech using PlayAI
const audio = await voice.speak('Hello, world!')
使用 AI SDK 模型 Provider使用 AI SDK 模型 Provider 的直接連結
你可以將 AI SDK 轉錄及語音模型直接傳入 CompositeVoice:
import { CompositeVoice } from '@mastra/core/voice'
import { openai } from '@ai-sdk/openai'
import { elevenlabs } from '@ai-sdk/elevenlabs'
// Use AI SDK models directly - they will be auto-wrapped
const voice = new CompositeVoice({
input: openai.transcription('whisper-1'), // AI SDK transcription
output: elevenlabs.speech('eleven_turbo_v2'), // AI SDK speech
})
// Works the same way as with Mastra providers
const text = await voice.listen(audioStream)
const audio = await voice.speak('Hello from AI SDK!')
混合配搭混合配搭 的直接連結
你可以組合 Mastra Provider 和 AI SDK 模型:
import { CompositeVoice } from '@mastra/core/voice'
import { PlayAIVoice } from '@mastra/voice-playai'
import { groq } from '@ai-sdk/groq'
const voice = new CompositeVoice({
input: groq.transcription('whisper-large-v3'), // AI SDK for STT
output: new PlayAIVoice(), // Mastra for TTS
})