Qwen3-ASR-0.6B与Vue3集成:开发网页端语音输入应用
你有没有想过,在网页上实现像手机语音助手那样的实时语音输入功能?比如,用户对着麦克风说话,网页就能实时把语音转成文字,显示在输入框里。这在客服聊天、语音搜索、会议记录等场景下特别有用。
以前做这个功能,要么得自己搭建复杂的语音识别服务,要么得依赖第三方API,成本高、延迟大,还不好控制。现在,有了Qwen3-ASR-0.6B这样的开源语音识别模型,情况就完全不一样了。这个模型不仅识别准确,支持多种语言和方言,而且体积小巧,性能高效,特别适合集成到前端应用里。
今天,我就来分享一下,怎么把Qwen3-ASR-0.6B和Vue3结合起来,快速搭建一个响应式的网页端语音输入应用。整个过程不复杂,跟着步骤走,你也能做出一个实用的语音输入功能。
1. 为什么选择Qwen3-ASR-0.6B和Vue3?
在开始动手之前,我们先简单了解一下为什么选这两个技术。
Qwen3-ASR-0.6B是阿里开源的语音识别模型,别看它只有0.6B参数,能力可不弱。它支持30种语言和22种中文方言的识别,在嘈杂环境下也能稳定工作。最关键的是,它支持流式推理,这意味着我们可以一边录音一边识别,实现真正的实时转写,延迟很低。而且它体积小,对部署环境要求不高,很适合我们这种前端集成的场景。
Vue3就不用多说了,现在是前端开发的主流框架之一。它的组合式API写起来特别灵活,响应式系统也很强大,非常适合处理像语音识别这种需要实时更新UI的交互场景。用Vue3来管理音频数据流、WebSocket连接和界面状态,代码会清晰很多。
把这两者结合起来,我们就能在前端实现一个高性能、低延迟的语音输入功能,而且完全可控,不需要依赖外部服务。
2. 整体架构设计
我们的应用大概是这样工作的:
- 用户在网页上点击“开始录音”按钮
- 浏览器通过
getUserMediaAPI获取麦克风权限并开始录音 - 前端将录音数据转换成合适的格式(比如PCM)
- 通过WebSocket连接,将音频数据流式发送到后端的Qwen3-ASR-0.6B服务
- 服务端实时识别音频,将识别结果通过WebSocket推回前端
- 前端实时显示识别出的文字
整个流程的关键在于“流式”处理。我们不是等用户说完一整段话再发送识别,而是一边录音一边发送,服务端也是一边接收一边识别,这样用户就能实时看到转写结果,体验更好。
下面是这个流程的简单示意图:
用户说话 → 浏览器录音 → 音频处理 → WebSocket发送 → 服务端识别 → WebSocket返回 → 前端显示
3. 前端实现:Vue3组件开发
我们先从前端开始,用Vue3搭建语音输入组件。
3.1 创建Vue3项目
如果你还没有Vue3项目,可以用Vite快速创建一个:
npm create vue@latest my-voice-app
cd my-voice-app
npm install
然后安装我们需要的依赖:
npm install axios
3.2 语音输入组件实现
接下来,我们创建一个语音输入组件。这个组件要处理录音、音频处理、WebSocket通信和界面交互。
<template>
<div class="voice-input-container">
<!-- 状态显示区域 -->
<div class="status-area">
<div class="status-indicator" :class="statusClass">
{{ statusText }}
</div>
<div v-if="isRecording" class="recording-indicator">
<span class="pulse"></span>
正在录音...
</div>
</div>
<!-- 控制按钮 -->
<div class="control-buttons">
<button
@click="toggleRecording"
:disabled="isConnecting"
:class="['record-btn', { 'recording': isRecording }]"
>
{{ isRecording ? '停止录音' : '开始录音' }}
</button>
<button
@click="clearText"
class="clear-btn"
:disabled="!transcribedText"
>
清空文本
</button>
</div>
<!-- 识别结果显示 -->
<div class="result-area">
<label for="transcription">识别结果:</label>
<textarea
id="transcription"
v-model="transcribedText"
readonly
placeholder="识别结果将显示在这里..."
class="transcription-textarea"
></textarea>
<div class="result-stats">
<span>识别字数:{{ textLength }}</span>
<span>连接状态:{{ connectionStatus }}</span>
</div>
</div>
<!-- 设置区域 -->
<div class="settings-area">
<div class="setting-item">
<label>
<input type="checkbox" v-model="autoScroll"> 自动滚动
</label>
</div>
<div class="setting-item">
<label>语言:</label>
<select v-model="selectedLanguage">
<option value="zh">中文</option>
<option value="en">英语</option>
<option value="ja">日语</option>
<option value="ko">韩语</option>
</select>
</div>
</div>
</div>
</template>
<script setup>
import { ref, computed, onUnmounted, watch } from 'vue'
// 响应式状态
const isRecording = ref(false)
const isConnecting = ref(false)
const transcribedText = ref('')
const autoScroll = ref(true)
const selectedLanguage = ref('zh')
const wsConnection = ref(null)
const mediaRecorder = ref(null)
const audioChunks = ref([])
// 计算属性
const statusText = computed(() => {
if (isConnecting.value) return '连接中...'
if (isRecording.value) return '录音中'
if (transcribedText.value) return '识别完成'
return '准备就绪'
})
const statusClass = computed(() => {
if (isRecording.value) return 'status-recording'
if (isConnecting.value) return 'status-connecting'
return 'status-ready'
})
const textLength = computed(() => transcribedText.value.length)
const connectionStatus = computed(() => wsConnection.value?.readyState === 1 ? '已连接' : '未连接')
// 切换录音状态
const toggleRecording = async () => {
if (isRecording.value) {
stopRecording()
} else {
await startRecording()
}
}
// 开始录音
const startRecording = async () => {
try {
// 获取麦克风权限
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
channelCount: 1, // 单声道
sampleRate: 16000, // 16kHz采样率
echoCancellation: true,
noiseSuppression: true
}
})
// 创建MediaRecorder
const options = {
mimeType: 'audio/webm;codecs=opus'
}
mediaRecorder.value = new MediaRecorder(stream, options)
audioChunks.value = []
// 收集音频数据
mediaRecorder.value.ondataavailable = (event) => {
if (event.data.size > 0) {
audioChunks.value.push(event.data)
sendAudioChunk(event.data)
}
}
// 开始录音
mediaRecorder.value.start(100) // 每100ms收集一次数据
isRecording.value = true
// 连接WebSocket
await connectWebSocket()
} catch (error) {
console.error('录音失败:', error)
alert('无法访问麦克风,请检查权限设置')
}
}
// 停止录音
const stopRecording = () => {
if (mediaRecorder.value && isRecording.value) {
mediaRecorder.value.stop()
mediaRecorder.value.stream.getTracks().forEach(track => track.stop())
mediaRecorder.value = null
isRecording.value = false
// 关闭WebSocket连接
if (wsConnection.value) {
wsConnection.value.close()
}
}
}
// 连接WebSocket
const connectWebSocket = () => {
return new Promise((resolve, reject) => {
isConnecting.value = true
// 这里替换成你的后端WebSocket地址
const wsUrl = 'ws://localhost:9000/ws/asr'
wsConnection.value = new WebSocket(wsUrl)
wsConnection.value.onopen = () => {
console.log('WebSocket连接已建立')
isConnecting.value = false
// 发送会话配置
const config = {
type: 'session.update',
session: {
modalities: ['text'],
input_audio_format: 'pcm',
sample_rate: 16000,
input_audio_transcription: {
language: selectedLanguage.value
},
turn_detection: {
type: 'server_vad',
threshold: 0.0,
silence_duration_ms: 400
}
}
}
wsConnection.value.send(JSON.stringify(config))
resolve()
}
wsConnection.value.onmessage = (event) => {
try {
const data = JSON.parse(event.data)
handleWebSocketMessage(data)
} catch (error) {
console.error('解析WebSocket消息失败:', error)
}
}
wsConnection.value.onerror = (error) => {
console.error('WebSocket错误:', error)
isConnecting.value = false
reject(error)
}
wsConnection.value.onclose = () => {
console.log('WebSocket连接已关闭')
isConnecting.value = false
}
})
}
// 处理WebSocket消息
const handleWebSocketMessage = (data) => {
switch (data.type) {
case 'conversation.item.input_audio_transcription.text':
// 实时转写结果
if (data.text) {
transcribedText.value += data.text
if (autoScroll.value) {
scrollToBottom()
}
}
break
case 'conversation.item.input_audio_transcription.completed':
// 最终转写结果
if (data.transcript) {
transcribedText.value = data.transcript
}
break
case 'input_audio_buffer.speech_started':
console.log('检测到语音开始')
break
case 'input_audio_buffer.speech_stopped':
console.log('检测到语音结束')
break
}
}
// 发送音频数据块
const sendAudioChunk = async (audioBlob) => {
if (!wsConnection.value || wsConnection.value.readyState !== WebSocket.OPEN) {
return
}
try {
// 将WebM/Opus转换为PCM
const pcmData = await convertToPCM(audioBlob)
// 发送音频数据
const message = {
type: 'input_audio_buffer.append',
audio: arrayBufferToBase64(pcmData)
}
wsConnection.value.send(JSON.stringify(message))
} catch (error) {
console.error('发送音频数据失败:', error)
}
}
// WebM/Opus转PCM(简化版,实际需要更完整的转换)
const convertToPCM = async (audioBlob) => {
// 这里简化处理,实际项目中需要使用AudioContext进行解码和重采样
// 为了示例,我们假设已经是PCM格式
return await audioBlob.arrayBuffer()
}
// ArrayBuffer转Base64
const arrayBufferToBase64 = (buffer) => {
let binary = ''
const bytes = new Uint8Array(buffer)
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i])
}
return btoa(binary)
}
// 清空文本
const clearText = () => {
transcribedText.value = ''
}
// 滚动到底部
const scrollToBottom = () => {
const textarea = document.querySelector('.transcription-textarea')
if (textarea) {
textarea.scrollTop = textarea.scrollHeight
}
}
// 组件卸载时清理资源
onUnmounted(() => {
if (isRecording.value) {
stopRecording()
}
if (wsConnection.value) {
wsConnection.value.close()
}
})
// 监听语言变化
watch(selectedLanguage, (newLang) => {
if (isRecording.value && wsConnection.value?.readyState === WebSocket.OPEN) {
// 更新会话配置
const config = {
type: 'session.update',
session: {
modalities: ['text'],
input_audio_format: 'pcm',
sample_rate: 16000,
input_audio_transcription: {
language: newLang
}
}
}
wsConnection.value.send(JSON.stringify(config))
}
})
</script>
<style scoped>
.voice-input-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
.status-area {
margin-bottom: 20px;
padding: 15px;
background: #f5f5f5;
border-radius: 8px;
}
.status-indicator {
display: inline-block;
padding: 6px 12px;
border-radius: 20px;
font-size: 14px;
font-weight: 500;
}
.status-ready {
background: #e8f5e9;
color: #2e7d32;
}
.status-recording {
background: #ffebee;
color: #c62828;
animation: pulse 1.5s infinite;
}
.status-connecting {
background: #fff3e0;
color: #ef6c00;
}
.recording-indicator {
margin-top: 10px;
display: flex;
align-items: center;
gap: 8px;
color: #c62828;
}
.pulse {
width: 12px;
height: 12px;
background: #c62828;
border-radius: 50%;
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.5; }
100% { opacity: 1; }
}
.control-buttons {
display: flex;
gap: 12px;
margin-bottom: 20px;
}
.record-btn {
flex: 1;
padding: 12px 24px;
font-size: 16px;
border: none;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s;
background: #2196f3;
color: white;
}
.record-btn:hover:not(:disabled) {
background: #1976d2;
transform: translateY(-1px);
}
.record-btn:disabled {
background: #ccc;
cursor: not-allowed;
}
.record-btn.recording {
background: #f44336;
}
.record-btn.recording:hover:not(:disabled) {
background: #d32f2f;
}
.clear-btn {
padding: 12px 24px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 8px;
cursor: pointer;
background: white;
transition: all 0.3s;
}
.clear-btn:hover:not(:disabled) {
background: #f5f5f5;
}
.clear-btn:disabled {
color: #999;
cursor: not-allowed;
}
.result-area {
margin-bottom: 20px;
}
.result-area label {
display: block;
margin-bottom: 8px;
font-weight: 500;
color: #333;
}
.transcription-textarea {
width: 100%;
min-height: 150px;
padding: 12px;
border: 1px solid #ddd;
border-radius: 8px;
font-size: 14px;
line-height: 1.5;
resize: vertical;
background: #fafafa;
}
.transcription-textarea:focus {
outline: none;
border-color: #2196f3;
box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.1);
}
.result-stats {
margin-top: 10px;
display: flex;
justify-content: space-between;
font-size: 12px;
color: #666;
}
.settings-area {
padding: 15px;
background: #f9f9f9;
border-radius: 8px;
border: 1px solid #eee;
}
.setting-item {
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 10px;
}
.setting-item:last-child {
margin-bottom: 0;
}
.setting-item label {
font-size: 14px;
color: #333;
}
.setting-item select {
padding: 6px 12px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
.setting-item input[type="checkbox"] {
margin-right: 6px;
}
</style>
这个组件实现了完整的语音输入功能,包括录音控制、实时转写显示、语言切换等。界面设计得比较简洁,但功能齐全。
4. 后端服务:Qwen3-ASR-0.6B部署与WebSocket接口
前端组件需要和后端的语音识别服务通信。我们需要部署Qwen3-ASR-0.6B,并提供一个WebSocket接口。
4.1 使用Docker快速部署
最简单的方式是用Docker部署。Qwen官方提供了预构建的镜像,我们可以直接使用。
首先,创建一个docker-compose.yml文件:
version: '3.8'
services:
qwen-asr:
image: qwen/qwen3-asr:0.6b-cpu
container_name: qwen-asr-service
ports:
- "9000:8000"
environment:
- MODEL_NAME=Qwen/Qwen3-ASR-0.6B
- DEVICE=cpu
- MAX_AUDIO_LENGTH=600
volumes:
- ./models:/app/models
command: >
python -m qwen_asr.serving.asr_server
--model_name_or_path ${MODEL_NAME}
--device ${DEVICE}
--host 0.0.0.0
--port 8000
--max_audio_length ${MAX_AUDIO_LENGTH}
--allow_credentials
--allowed_origins "*"
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3
然后运行:
docker-compose up -d
这样就在本地的9000端口启动了一个语音识别服务。这个服务会提供WebSocket接口,用于实时语音识别。
4.2 创建WebSocket代理服务
由于浏览器的安全限制,我们通常需要一个中间层来代理WebSocket连接。这里我用Node.js写一个简单的代理服务:
// server.js
const express = require('express')
const http = require('http')
const WebSocket = require('ws')
const cors = require('cors')
const app = express()
const server = http.createServer(app)
// 启用CORS
app.use(cors())
app.use(express.json())
// ASR服务配置
const ASR_SERVICE_URL = 'ws://localhost:8000/ws'
const ASR_SERVICE_TIMEOUT = 30000 // 30秒超时
// 存储活跃的连接
const activeConnections = new Map()
// 创建WebSocket服务器
const wss = new WebSocket.Server({ server, path: '/ws/asr' })
wss.on('connection', (clientWs, request) => {
console.log('新的客户端连接:', request.socket.remoteAddress)
// 连接到ASR服务
let asrWs = null
let connectionId = Date.now().toString()
const connectToASR = () => {
asrWs = new WebSocket(ASR_SERVICE_URL)
// 设置超时
const timeoutId = setTimeout(() => {
if (asrWs.readyState !== WebSocket.OPEN) {
console.error('连接ASR服务超时')
clientWs.close(1008, '连接超时')
asrWs?.close()
}
}, ASR_SERVICE_TIMEOUT)
asrWs.on('open', () => {
console.log(`连接 ${connectionId}: 已连接到ASR服务`)
clearTimeout(timeoutId)
activeConnections.set(connectionId, { clientWs, asrWs })
// 发送连接成功消息
clientWs.send(JSON.stringify({
type: 'connection.established',
connectionId,
timestamp: new Date().toISOString()
}))
})
asrWs.on('message', (data) => {
try {
// 转发ASR服务的消息到客户端
if (clientWs.readyState === WebSocket.OPEN) {
clientWs.send(data.toString())
}
} catch (error) {
console.error('转发消息失败:', error)
}
})
asrWs.on('error', (error) => {
console.error(`连接 ${connectionId}: ASR服务错误`, error)
clientWs.send(JSON.stringify({
type: 'error',
message: 'ASR服务连接错误',
code: 'ASR_CONNECTION_ERROR'
}))
})
asrWs.on('close', (code, reason) => {
console.log(`连接 ${connectionId}: ASR服务连接关闭`, code, reason.toString())
activeConnections.delete(connectionId)
// 通知客户端
if (clientWs.readyState === WebSocket.OPEN) {
clientWs.send(JSON.stringify({
type: 'connection.closed',
code,
reason: reason.toString(),
timestamp: new Date().toISOString()
}))
}
})
}
// 处理客户端消息
clientWs.on('message', (data) => {
try {
const message = JSON.parse(data.toString())
// 如果是会话配置消息,添加必要的信息
if (message.type === 'session.update') {
// 确保音频格式和采样率设置正确
if (!message.session.input_audio_format) {
message.session.input_audio_format = 'pcm'
}
if (!message.session.sample_rate) {
message.session.sample_rate = 16000
}
}
// 转发到ASR服务
if (asrWs && asrWs.readyState === WebSocket.OPEN) {
asrWs.send(JSON.stringify(message))
}
} catch (error) {
console.error('处理客户端消息失败:', error)
clientWs.send(JSON.stringify({
type: 'error',
message: '消息格式错误',
code: 'INVALID_MESSAGE_FORMAT'
}))
}
})
clientWs.on('error', (error) => {
console.error(`连接 ${connectionId}: 客户端错误`, error)
})
clientWs.on('close', (code, reason) => {
console.log(`连接 ${connectionId}: 客户端连接关闭`, code, reason.toString())
// 清理资源
if (asrWs) {
asrWs.close()
}
activeConnections.delete(connectionId)
})
// 开始连接ASR服务
connectToASR()
})
// 健康检查端点
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
activeConnections: activeConnections.size
})
})
// 获取服务状态
app.get('/status', (req, res) => {
const connections = Array.from(activeConnections.entries()).map(([id, conn]) => ({
id,
clientState: conn.clientWs.readyState,
asrState: conn.asrWs?.readyState || 'disconnected',
clientIp: conn.clientWs._socket?.remoteAddress
}))
res.json({
totalConnections: activeConnections.size,
connections,
serverTime: new Date().toISOString()
})
})
// 错误处理中间件
app.use((err, req, res, next) => {
console.error('服务器错误:', err)
res.status(500).json({
error: '服务器内部错误',
message: process.env.NODE_ENV === 'development' ? err.message : undefined
})
})
// 启动服务器
const PORT = process.env.PORT || 3000
server.listen(PORT, () => {
console.log(`WebSocket代理服务运行在 http://localhost:${PORT}`)
console.log(`WebSocket端点: ws://localhost:${PORT}/ws/asr`)
console.log(`健康检查: http://localhost:${PORT}/health`)
})
// 优雅关闭
process.on('SIGTERM', () => {
console.log('收到SIGTERM信号,开始关闭服务器...')
// 关闭所有WebSocket连接
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.close(1001, '服务器关闭')
}
})
// 关闭所有ASR连接
activeConnections.forEach(({ asrWs }) => {
if (asrWs && asrWs.readyState === WebSocket.OPEN) {
asrWs.close()
}
})
server.close(() => {
console.log('服务器已关闭')
process.exit(0)
})
})
这个代理服务做了几件事:
- 提供WebSocket端点 (
/ws/asr) 供前端连接 - 代理前端和ASR服务之间的消息
- 添加了一些错误处理和日志
- 提供了健康检查接口
安装依赖:
npm install express ws cors
然后运行:
node server.js
现在,前端组件就可以连接到 ws://localhost:3000/ws/asr 了。
5. 音频处理优化
在实际使用中,浏览器的录音格式(通常是WebM/Opus)需要转换成ASR服务需要的格式(PCM)。上面的前端代码中,我简化了这个转换过程。实际上,我们需要更完整的处理。
这里是一个更完整的音频转换函数:
// audio-processor.js
class AudioProcessor {
constructor() {
this.audioContext = null
this.sourceNode = null
this.scriptNode = null
this.sampleRate = 16000
this.channels = 1
}
// 初始化AudioContext
init() {
if (!this.audioContext) {
this.audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: this.sampleRate
})
}
}
// 将WebM/Opus转换为PCM
async convertToPCM(audioBlob) {
this.init()
try {
// 1. 将Blob转换为ArrayBuffer
const arrayBuffer = await audioBlob.arrayBuffer()
// 2. 解码音频
const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer)
// 3. 如果已经是单声道且16kHz,直接返回
if (audioBuffer.sampleRate === this.sampleRate && audioBuffer.numberOfChannels === this.channels) {
return audioBuffer.getChannelData(0)
}
// 4. 创建离线上下文进行重采样
const offlineContext = new OfflineAudioContext(
this.channels,
audioBuffer.duration * this.sampleRate,
this.sampleRate
)
// 5. 创建源节点
const source = offlineContext.createBufferSource()
source.buffer = audioBuffer
source.connect(offlineContext.destination)
source.start()
// 6. 渲染音频
const renderedBuffer = await offlineContext.startRendering()
// 7. 获取PCM数据
const pcmData = renderedBuffer.getChannelData(0)
// 8. 转换为Int16Array
const int16Data = this.floatToInt16(pcmData)
return int16Data.buffer
} catch (error) {
console.error('音频转换失败:', error)
throw error
}
}
// 浮点数转Int16
floatToInt16(floatArray) {
const int16Array = new Int16Array(floatArray.length)
for (let i = 0; i < floatArray.length; i++) {
let val = Math.floor(floatArray[i] * 32767)
val = Math.max(-32768, Math.min(32767, val))
int16Array[i] = val
}
return int16Array
}
// 实时音频处理
startRealTimeProcessing(stream, onData) {
this.init()
// 创建媒体流源
this.sourceNode = this.audioContext.createMediaStreamSource(stream)
// 创建处理器节点
this.scriptNode = this.audioContext.createScriptProcessor(4096, this.channels, this.channels)
this.scriptNode.onaudioprocess = (audioProcessingEvent) => {
const inputBuffer = audioProcessingEvent.inputBuffer
const channelData = inputBuffer.getChannelData(0)
// 转换为Int16
const int16Data = this.floatToInt16(channelData)
// 回调处理数据
if (onData) {
onData(int16Data.buffer)
}
}
// 连接节点
this.sourceNode.connect(this.scriptNode)
this.scriptNode.connect(this.audioContext.destination)
}
// 停止处理
stopProcessing() {
if (this.scriptNode) {
this.scriptNode.disconnect()
this.scriptNode = null
}
if (this.sourceNode) {
this.sourceNode.disconnect()
this.sourceNode = null
}
}
// 清理资源
dispose() {
this.stopProcessing()
if (this.audioContext && this.audioContext.state !== 'closed') {
this.audioContext.close()
}
this.audioContext = null
}
}
export default AudioProcessor
在前端组件中使用这个处理器:
import AudioProcessor from './audio-processor.js'
// 在组件中
const audioProcessor = new AudioProcessor()
// 修改录音开始函数
const startRecording = async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
channelCount: 1,
sampleRate: 16000,
echoCancellation: true,
noiseSuppression: true
}
})
// 使用AudioProcessor进行实时处理
audioProcessor.startRealTimeProcessing(stream, (audioBuffer) => {
sendAudioChunk(audioBuffer)
})
isRecording.value = true
await connectWebSocket()
} catch (error) {
console.error('录音失败:', error)
alert('无法访问麦克风,请检查权限设置')
}
}
// 修改停止录音函数
const stopRecording = () => {
if (isRecording.value) {
audioProcessor.stopProcessing()
isRecording.value = false
if (wsConnection.value) {
wsConnection.value.close()
}
}
}
这样,音频处理就更完整了,能确保发送给ASR服务的是正确的PCM格式。
6. 实际应用与优化建议
现在,一个完整的语音输入应用就搭建好了。你可以运行前端Vue应用和后端服务,试试效果。
在实际使用中,你可能还会遇到一些问题,这里分享几个优化建议:
6.1 网络延迟优化
语音识别对延迟比较敏感。如果用户感觉转写有明显的延迟,可以尝试:
- 减少音频块大小:前端发送更小的音频块,比如每50ms发送一次
- 使用更快的网络:确保前后端在同一局域网,或者使用CDN
- 压缩音频数据:在发送前对PCM数据进行压缩(比如使用GZIP)
6.2 错误处理增强
实际使用中,网络可能不稳定,服务可能出错。需要增强错误处理:
// 在前端组件中添加重试逻辑
const MAX_RETRIES = 3
let retryCount = 0
const connectWebSocketWithRetry = async () => {
try {
await connectWebSocket()
retryCount = 0 // 连接成功,重置重试计数
} catch (error) {
if (retryCount < MAX_RETRIES) {
retryCount++
console.log(`连接失败,第${retryCount}次重试...`)
setTimeout(() => connectWebSocketWithRetry(), 1000 * retryCount) // 指数退避
} else {
console.error('连接失败,已达到最大重试次数')
alert('无法连接到语音识别服务,请检查网络连接')
}
}
}
6.3 性能监控
添加性能监控,了解应用运行状况:
// 监控关键指标
const performanceMetrics = {
startTime: null,
audioSent: 0,
messagesReceived: 0,
latencySamples: []
}
// 在发送音频时记录
const sendAudioChunk = async (audioBuffer) => {
const start = performance.now()
// ... 发送逻辑
const end = performance.now()
const latency = end - start
performanceMetrics.latencySamples.push(latency)
// 保持最近100个样本
if (performanceMetrics.latencySamples.length > 100) {
performanceMetrics.latencySamples.shift()
}
}
// 计算平均延迟
const getAverageLatency = () => {
if (performanceMetrics.latencySamples.length === 0) return 0
const sum = performanceMetrics.latencySamples.reduce((a, b) => a + b, 0)
return sum / performanceMetrics.latencySamples.length
}
6.4 移动端适配
在移动设备上,需要考虑:
- 触摸交互:录音按钮要足够大,方便触摸
- 省电模式:长时间录音时,注意电量消耗
- 后台运行:应用切换到后台时,正确处理录音和连接
7. 扩展功能
这个基础应用可以扩展很多实用功能:
7.1 语音命令识别
除了转写,还可以识别特定命令:
// 在后端添加命令识别逻辑
const recognizedCommands = {
'清空屏幕': 'clear',
'保存内容': 'save',
'发送消息': 'send',
// ... 更多命令
}
// 在转写结果中检测命令
const checkForCommands = (text) => {
for (const [command, action] of Object.entries(recognizedCommands)) {
if (text.includes(command)) {
return { command, action }
}
}
return null
}
7.2 多语言实时切换
让用户可以在说话过程中切换语言:
// 前端发送语言切换请求
const switchLanguage = (newLanguage) => {
if (wsConnection.value?.readyState === WebSocket.OPEN) {
const message = {
type: 'session.update',
session: {
input_audio_transcription: {
language: newLanguage
}
}
}
wsConnection.value.send(JSON.stringify(message))
}
}
7.3 语音反馈
识别完成后,用语音读出来:
const speakText = (text) => {
if ('speechSynthesis' in window) {
const utterance = new SpeechSynthesisUtterance(text)
utterance.lang = selectedLanguage.value
utterance.rate = 1.0
speechSynthesis.speak(utterance)
}
}
// 在识别完成时调用
if (data.type === 'conversation.item.input_audio_transcription.completed') {
transcribedText.value = data.transcript
speakText(data.transcript) // 语音反馈
}
8. 总结
整体用下来,Qwen3-ASR-0.6B和Vue3的集成效果还是挺不错的。部署过程比想象中简单,Docker镜像一键就能跑起来。前端的实现虽然有些细节要注意,但整体逻辑清晰,Vue3的响应式系统处理这种实时数据流特别合适。
实际体验上,识别准确率在安静环境下很好,嘈杂环境下的表现也超出预期。延迟方面,在局域网内基本感觉不到延迟,实时性很好。如果是在公网环境下,可能需要对音频块大小和发送频率做些调整。
这个方案最大的优点是可控性强。所有的组件都在自己手里,从录音、传输到识别,整个流程都可以按需调整。而且Qwen3-ASR-0.6B是开源的,不用担心API调用限制或者费用问题。
如果你正在考虑为你的Web应用添加语音输入功能,这个方案值得一试。先从简单的场景开始,比如语音搜索或者表单填写,等跑通了再扩展到更复杂的应用。过程中遇到问题,可以多看看浏览器的开发者工具和后台日志,大部分问题都能找到原因。
获取更多AI镜像
想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。




被折叠的 条评论
为什么被折叠?



