跳至主要內容

語音轉文字(STT)

Mastra 的語音轉文字(STT)提供標準化介面,可透過多個服務 Provider 將音訊輸入轉換成文字。 STT 讓具備語音功能的應用程式能回應人類語音。它支援免持互動、改善身心障礙使用者的無障礙體驗,也能提供更自然的介面。

設定
「設定」的直接連結

若要在 Mastra 中使用 STT,初始化 Voice Provider 時必須提供 listeningModel,其中可包含以下參數:

  • name:要使用的特定 STT 模型。
  • apiKey:用於身分驗證的 API 金鑰。
  • Provider 特有選項:特定 Voice Provider 可能需要或支援的其他選項。

行為:這些參數均為選填。你可以使用 Voice Provider 提供的預設設定;實際預設值取決於所使用的 Provider。

const voice = new OpenAIVoice({
listeningModel: {
name: 'whisper-1',
apiKey: process.env.OPENAI_API_KEY,
},
})

// If using default settings the configuration can be simplified to:
const voice = new OpenAIVoice()

可用的 Provider
「可用的 Provider」的直接連結

Mastra 支援多個語音轉文字 Provider,各自具有不同的功能與優勢:

  • OpenAI:使用 Whisper 模型進行高準確度轉錄
  • Azure:Microsoft 的語音辨識,具備企業級可靠性
  • ElevenLabs:支援多種語言的進階語音辨識
  • Google:Google 的語音辨識,廣泛支援多種語言
  • Cloudflare:針對低延遲應用程式進行邊緣最佳化的語音辨識
  • Deepgram:AI 驅動的語音辨識,能以高準確度處理各種口音
  • Sarvam:專精於印度語言與口音

每個 Provider 都以獨立套件實作,你可以視需要安裝:

pnpm add @mastra/voice-openai@latest # Example for OpenAI

使用 listen 方法
「使用 listen 方法」的直接連結

STT 的主要方法是 listen(),可將語音音訊轉換成文字。用法如下:

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

const voice = new OpenAIVoice()

const agent = new Agent({
id: 'voice-agent',
name: 'Voice Agent',
instructions: 'You are a voice assistant that provides recommendations based on user input.',
model: 'openai/gpt-5.6-sol',
voice,
})

const audioStream = getMicrophoneStream() // Assume this function gets audio input

const transcript = await agent.voice.listen(audioStream, {
filetype: 'm4a', // Optional: specify the audio file type
})

console.log(`User said: ${transcript}`)

const { text } = await agent.generate(
`Based on what the user said, provide them a recommendation: ${transcript}`,
)

console.log(`Recommendation: ${text}`)

轉錄音訊檔案
「轉錄音訊檔案」的直接連結

listen() 方法接受來自麥克風或檔案的音訊資料串流。若要轉錄音訊檔案,請使用 createReadStream()

import { createReadStream } from 'fs'
import path from 'path'

const audioFilePath = path.join(process.cwd(), 'agent.m4a')
const audioStream = createReadStream(audioFilePath)

const transcription = await agent.voice.listen(audioStream, {
filetype: 'm4a',
})

console.log(`Transcription: ${transcription}`)

如需 Agent 上 Voice Provider 的整體概覽,請參閱 Mastra 中的 Voice