注意:此文档是基于 uniapp 开发微信小程序的总结
微信小程序实现语音实时转文字功能,引入微信小程序自研的同声传译插件(官方文档:插件服务 / 微信同声传译)
引入
1. 小程序后台
微信小程序后台-> 设置->第三方设置-> 插件管理(添加插件)-> 搜索微信同声传译
2. maneifest.json
下面一段代码添加到mp-weixin,version,provider在插件管理中可以看到具体信息
"plugins": {
"WechatSI": {
"version": "0.3.6",
"provider": "wx069ba97219f66d99"
}
}
完整流程图
实现流程
1. 核心界面实现
<view class="input-container">
<image
class="record-icon"
:class="{ 'recording': isRecording }"
src="/static/icon/record.png"
mode="aspectFit"
@click="toggleRecording"
></image>
<input
class="message-input"
v-model="inputMessage"
:placeholder="inputPlaceholder"
:disabled="isLoading"
@confirm="sendMessage"
confirm-type="send"
/>
<button
class="send-btn"
:class="{ 'send-btn-disabled': !inputMessage.trim() || isLoading }"
@click="sendMessage"
:disabled="!inputMessage.trim() || isLoading"
>
<text v-if="!isLoading">发送</text>
<text v-else>...</text>
</button>
</view>
2. 变量添加
// 录音相关
isRecording: false, // 是否正在录音
plugin: null, // 微信同声传译插件实例
manager: null // 录音管理器
3. 页面加载
onLoad(options) {
// 初始化微信同声传译插件
this.initVoicePlugin()
},
/**
* 初始化微信同声传译插件
*/
initVoicePlugin() {
try {
// 引入微信同声传译插件
this.plugin = requirePlugin("WechatSI")
// 获取录音管理器
this.manager = this.plugin.getRecordRecognitionManager()
// 监听识别开始事件
this.manager.onStart = (res) => {
console.log('录音识别开始', res)
this.isRecording = true
}
// 监听识别结果事件(实时返回)
this.manager.onRecognize = (res) => {
console.log('实时识别结果:', res)
if (res.result) {
// 实时更新到输入框
this.inputMessage = res.result
}
}
// 监听识别结束事件
this.manager.onStop = (res) => {
console.log('录音识别结束', res)
this.isRecording = false
if (res.result) {
// 最终结果更新到输入框
this.inputMessage = res.result
}
}
// 监听识别错误事件
this.manager.onError = (res) => {
console.error('录音识别错误:', res)
this.isRecording = false
uni.showToast({
title: '识别失败,请重试',
icon: 'none',
duration: 2000
})
}
} catch (error) {
console.error('微信同声传译插件初始化失败:', error)
uni.showToast({
title: '语音功能不可用',
icon: 'none',
duration: 2000
})
}
console.warn('当前环境不支持微信同声传译插件')
},
4. 用户点击录音按钮
/**
* 切换录音状态
*/
toggleRecording() {
if (!this.manager) {
uni.showToast({
title: '语音功能未初始化',
icon: 'none',
duration: 2000
})
return
}
if (this.isRecording) {
// 停止录音
this.stopRecording()
} else {
// 开始录音
this.startRecording()
}
uni.showToast({
title: '仅支持微信小程序',
icon: 'none',
duration: 2000
})
},
/**
* 开始录音
*/
startRecording() {
try {
// 先清空输入框
this.inputMessage = ''
// 开始录音识别
this.manager.start({
duration: 60000, // 最长录音时长(毫秒)
lang: 'zh_CN' // 语言:中文
})
uni.showToast({
title: '开始录音...',
icon: 'none',
duration: 1000
})
} catch (error) {
console.error('开始录音失败:', error)
this.isRecording = false
uni.showToast({
title: '录音失败,请重试',
icon: 'none',
duration: 2000
})
}
},
/**
* 停止录音
*/
stopRecording() {
try {
this.manager.stop()
uni.showToast({
title: '录音结束',
icon: 'none',
duration: 1000
})
} catch (error) {
console.error('停止录音失败:', error)
this.isRecording = false
}
},
5. 切换页面
onUnload() {
// 清理录音资源
if (this.manager) {
this.manager.stop()
}
},