OpenAI
VoiceVoice的直接链接
The OpenAIVoice class in Mastra provides text-to-speech and speech-to-text capabilities using OpenAI's models.
Usage exampleUsage example的直接链接
import { OpenAIVoice } from '@mastra/voice-openai'
// Initialize with default configuration using environment variables
const voice = new OpenAIVoice()
// Or initialize with specific configuration
const voiceWithConfig = new OpenAIVoice({
speechModel: {
name: 'tts-1-hd',
apiKey: 'your-openai-api-key',
},
listeningModel: {
name: 'whisper-1',
apiKey: 'your-openai-api-key',
},
speaker: 'alloy', // Default voice
})
// Convert text to speech
const audioStream = await voice.speak('Hello, how can I help you?', {
speaker: 'nova', // Override default voice
speed: 1.2, // Adjust speech speed
})
// Convert speech to text
const text = await voice.listen(audioStream, {
filetype: 'mp3',
})
ConfigurationConfiguration的直接链接
Constructor optionsConstructor options的直接链接
speechModel?:
name?:
apiKey?:
listeningModel?:
name?:
apiKey?:
speaker?:
MethodsMethods的直接链接
speak()speak的直接链接
Converts text to speech using OpenAI's text-to-speech models.
input:
options?:
speaker?:
speed?:
Returns: Promise<NodeJS.ReadableStream>
listen()listen的直接链接
Transcribes audio using OpenAI's Whisper model.
audioStream:
options?:
filetype?:
Returns: Promise<string>
getSpeakers()getspeakers的直接链接
Returns an array of available voice options, where each node contains:
voiceId:
NotesNotes的直接链接
- API keys can be provided via constructor options or the
OPENAI_API_KEYenvironment variable - The
tts-1-hdmodel provides higher quality audio but may have slower processing times - Speech recognition supports multiple audio formats including mp3, wav, and webm
RealtimeRealtime的直接链接
The OpenAIRealtimeVoice class provides real-time voice interaction capabilities using OpenAI's WebSocket-based API. It supports real time speech to speech, voice activity detection, and event-based audio streaming.
Usage exampleUsage example的直接链接
import { OpenAIRealtimeVoice } from '@mastra/voice-openai-realtime'
import { playAudio, getMicrophoneStream } from '@mastra/node-audio'
// Initialize with default configuration using environment variables
const voice = new OpenAIRealtimeVoice()
// Or initialize with specific configuration
const voiceWithConfig = new OpenAIRealtimeVoice({
apiKey: 'your-openai-api-key',
model: 'gpt-5.1-realtime-preview-2024-12-17',
speaker: 'alloy', // Default voice
})
voiceWithConfig.updateSession({
turn_detection: {
type: 'server_vad',
threshold: 0.6,
silence_duration_ms: 1200,
},
})
// Establish connection
await voice.connect()
// Set up event listeners
voice.on('speaker', ({ audio }) => {
// Handle audio data (Int16Array) pcm format by default
playAudio(audio)
})
voice.on('writing', ({ text, role }) => {
// Handle transcribed text
console.log(`${role}: ${text}`)
})
// Convert text to speech
await voice.speak('Hello, how can I help you today?', {
speaker: 'echo', // Override default voice
})
// Process audio input
const microphoneStream = getMicrophoneStream()
await voice.send(microphoneStream)
// When done, disconnect
voice.connect()
ConfigurationConfiguration的直接链接
Constructor optionsConstructor options的直接链接
model?:
apiKey?:
speaker?:
Voice Activity Detection (VAD) ConfigurationVoice Activity Detection (VAD) Configuration的直接链接
type?:
threshold?:
prefix_padding_ms?:
silence_duration_ms?:
MethodsMethods的直接链接
connect()connect的直接链接
Establishes a connection to the OpenAI Realtime service. Must be called before using speak, listen, or send functions.
returns:
speak()speak-1的直接链接
Emits a speaking event using the configured voice model. Can accept either a string or a readable stream as input.
input:
options?:
speaker?:
Returns: Promise<void>
listen()listen-1的直接链接
Processes audio input for speech recognition. Takes a readable stream of audio data and emits a 'listening' event with the transcribed text.
audioData:
Returns: Promise<void>
send()send的直接链接
Streams audio data in real-time to the OpenAI service for continuous audio streaming scenarios like live microphone input.
audioData:
Returns: Promise<void>
updateConfig()updateconfig的直接链接
Updates the session configuration for the voice instance. This can modify voice settings and turn detection. It can also modify other parameters.
sessionConfig:
Returns: void
addTools()addtools的直接链接
Adds a set of tools to the voice instance. Tools allow the model to perform additional actions during conversations. When OpenAIRealtimeVoice is added to an Agent, any tools configured for the Agent will automatically be available to the voice interface.
tools?:
Returns: void
close()close的直接链接
Disconnects from the OpenAI Realtime session and cleans up resources. Should be called when you're done with the voice instance.
Returns: void
sendEvent()sendevent的直接链接
Sends a raw client event to the OpenAI Realtime session. Use this for session control that has no dedicated method, such as adding conversation items. Events sent before the session is created are queued and sent once it is.
type:
data?:
Returns: void
getSpeakers()getspeakers-1的直接链接
Returns a list of available voice speakers.
Returns: Promise<Array<{ voiceId: string; [key: string]: any }>>
on()on的直接链接
Registers an event listener for voice events.
event:
callback:
Returns: void
off()off的直接链接
Removes a previously registered event listener.
event:
callback:
Returns: void
EventsEvents的直接链接
The OpenAIRealtimeVoice class emits the following events:
speaking:
writing:
error:
OpenAI Realtime EventsOpenAI Realtime Events的直接链接
Every server event received from the OpenAI Realtime API is also emitted with the openAIRealtime: prefix, using the OpenAI server event type as the suffix. The callback receives the complete event payload.
voice.on('openAIRealtime:rate_limits.updated', event => {
console.log(event.rate_limits)
})
Socket EventsSocket Events的直接链接
open:
close:
Available voicesAvailable voices的直接链接
The following voice options are available:
alloy: Neutral and balancedash: Clear and preciseballad: Melodic and smoothcoral: Warm and friendlyecho: Resonant and deepsage: Calm and thoughtfulshimmer: Bright and energeticverse: Versatile and expressive
NotesNotes的直接链接
- API keys can be provided via constructor options or the
OPENAI_API_KEYenvironment variable - The OpenAI Realtime Voice API uses WebSockets for real-time communication
- Server-side Voice Activity Detection (VAD) provides better accuracy for speech detection
- All audio data is processed as Int16Array format
- The voice instance must be connected with
connect()before using other methods - Always call
close()when done to properly clean up resources - Memory management is handled by OpenAI Realtime API