跳至主要內容

Mastra 中的 Voice

Mastra 的 Voice 系統提供統一的語音互動介面,讓應用程式能使用文字轉語音(TTS)、語音轉文字(STT)及即時語音轉語音(STS)功能。

為 Agent 加入 Voice
「為 Agent 加入 Voice」的直接連結

使用 voice 屬性將 Voice Provider 傳入 Agent。依所設定的 Provider 而定,相同屬性可支援文字轉語音(TTS)、語音轉文字(STT)及即時語音轉語音(STS)。

import { Agent } from '@mastra/core/agent'
import { OpenAIVoice } from '@mastra/voice-openai'

// Initialize OpenAI voice for TTS

const voiceAgent = 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: new OpenAIVoice(),
})

接著即可使用下列 Voice 功能:

文字轉語音(TTS)
「文字轉語音(TTS)」的直接連結

使用 Mastra 的 TTS 功能,將 Agent 回應轉換成自然的語音。 你可以從 OpenAI、ElevenLabs 等多個 Provider 中選擇。

如需詳細設定選項與進階功能,請參閱文字轉語音指南

import { Agent } from '@mastra/core/agent'
import { OpenAIVoice } from '@mastra/voice-openai'
import { playAudio } from '@mastra/node-audio'

const voiceAgent = 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: new OpenAIVoice(),
})

const { text } = await voiceAgent.generate('What color is the sky?')

// Convert text to speech to an Audio Stream
const audioStream = await voiceAgent.voice.speak(text, {
speaker: 'default', // Optional: specify a speaker
responseFormat: 'wav', // Optional: specify a response format
})

playAudio(audioStream)

如需 OpenAI Voice Provider 的詳細資訊,請參閱 OpenAI Voice 參考文件

語音轉文字(STT)
「語音轉文字(STT)」的直接連結

使用 OpenAI、ElevenLabs 等 Provider 轉錄語音內容。如需詳細設定選項與其他資訊,請參閱語音轉文字

你可以從此處下載音訊範例檔案。


import { Agent } from '@mastra/core/agent'
import { OpenAIVoice } from '@mastra/voice-openai'
import { createReadStream } from 'fs'

const voiceAgent = 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: new OpenAIVoice(),
})

// Use an audio file from a URL
const audioStream = await createReadStream('./how_can_i_help_you.mp3')

// Convert audio to text
const transcript = await voiceAgent.voice.listen(audioStream)
console.log(`User said: ${transcript}`)

// Generate a response based on the transcript
const { text } = await voiceAgent.generate(transcript)

如需 OpenAI Voice Provider 的詳細資訊,請參閱 OpenAI Voice 參考文件

語音轉語音(STS)
「語音轉語音(STS)」的直接連結

運用語音轉語音功能建立對話體驗。統一 API 能讓使用者與 AI Agent 進行即時語音互動。 如需詳細設定選項與進階功能,請參閱語音轉語音

import { Agent } from '@mastra/core/agent'
import { playAudio, getMicrophoneStream } from '@mastra/node-audio'
import { OpenAIRealtimeVoice } from '@mastra/voice-openai-realtime'

const voiceAgent = 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: new OpenAIRealtimeVoice(),
})

// Listen for agent audio responses
voiceAgent.voice.on('speaker', ({ audio }) => {
playAudio(audio)
})

// Initiate the conversation
await voiceAgent.voice.speak('How can I help you today?')

// Send continuous audio from the microphone
const micStream = getMicrophoneStream()
await voiceAgent.voice.send(micStream)

如需 OpenAI Voice Provider 的詳細資訊,請參閱 OpenAI Voice 參考文件

即時 Voice
「即時 Voice」的直接連結

在瀏覽器或電話上執行使用者可隨時插話的即時通話。Mastra 將音訊迴圈交由 LiveKit 處理語音活動偵測、語意回合偵測與插話,而 Agent 則使用自己的模型、Tool 與 Memory 產生每次回應。設定方式與選項請參閱即時 Voice

Voice 設定
「Voice 設定」的直接連結

每個 Voice Provider 都能設定不同模型與選項。以下列出所有支援 Provider 的詳細設定選項:

// OpenAI Voice Configuration
const voice = new OpenAIVoice({
speechModel: {
name: 'gpt-3.5-turbo', // Example model name
apiKey: process.env.OPENAI_API_KEY,
language: 'en-US', // Language code
voiceType: 'neural', // Type of voice model
},
listeningModel: {
name: 'whisper-1', // Example model name
apiKey: process.env.OPENAI_API_KEY,
language: 'en-US', // Language code
format: 'wav', // Audio format
},
speaker: 'alloy', // Example speaker name
})

如需 OpenAI Voice Provider 的詳細資訊,請參閱 OpenAI Voice 參考文件

使用多個 Voice Provider
「使用多個 Voice Provider」的直接連結

此範例示範如何在 Mastra 中建立及使用兩個不同的 Voice Provider:使用 OpenAI 進行語音轉文字(STT),並使用 PlayAI 進行文字轉語音(TTS)。

首先建立 Voice Provider 執行個體,並加入所需設定。

import { OpenAIVoice } from '@mastra/voice-openai'
import { PlayAIVoice } from '@mastra/voice-playai'
import { CompositeVoice } from '@mastra/core/voice'
import { playAudio, getMicrophoneStream } from '@mastra/node-audio'

// Initialize OpenAI voice for STT
const input = new OpenAIVoice({
listeningModel: {
name: 'whisper-1',
apiKey: process.env.OPENAI_API_KEY,
},
})

// Initialize PlayAI voice for TTS
const output = new PlayAIVoice({
speechModel: {
name: 'playai-voice',
apiKey: process.env.PLAYAI_API_KEY,
},
})

// Combine the providers using CompositeVoice
const voice = new CompositeVoice({
input,
output,
})

// Implement voice interactions using the combined voice provider
const audioStream = getMicrophoneStream() // Assume this function gets audio input
const transcript = await voice.listen(audioStream)

// Log the transcribed text
console.log('Transcribed text:', transcript)

// Convert text to speech
const responseAudio = await voice.speak(`You said: ${transcript}`, {
speaker: 'default', // Optional: specify a speaker,
responseFormat: 'wav', // Optional: specify a response format
})

// Play the audio response
playAudio(responseAudio)

使用 AI SDK 模型 Provider
「使用 AI SDK 模型 Provider」的直接連結

你也可以直接搭配 CompositeVoice 使用 AI SDK 模型:

import { CompositeVoice } from '@mastra/core/voice'
import { openai } from '@ai-sdk/openai'
import { elevenlabs } from '@ai-sdk/elevenlabs'
import { playAudio, getMicrophoneStream } from '@mastra/node-audio'

// Use AI SDK models directly - no provider setup needed
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 Mastra providers
const audioStream = getMicrophoneStream()
const transcript = await voice.listen(audioStream)

console.log('Transcribed text:', transcript)

// Convert text to speech
const responseAudio = await voice.speak(`You said: ${transcript}`, {
speaker: 'Rachel', // ElevenLabs voice
})

playAudio(responseAudio)

你也可以混合使用 AI SDK 模型與 Mastra Provider:

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 provider for TTS
})

如需 CompositeVoice 的詳細資訊,請參閱 CompositeVoice 參考文件

更多資源
「更多資源」的直接連結