跳至主要內容

語音轉文字(STT)

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

設定
設定 的直接連結

要在 Mastra 使用 STT,初始化語音 Provider 時需提供 listeningModel,當中包括以下參數:

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

行為:以上參數全部均為選填。你可以使用語音 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 語音 Provider 的完整概覽,請參閱 Mastra 中的 Voice