wechat-si-recognition
v1.0.0
Published
微信小程序同声传译语音识别 Hook,含录音权限处理,适用于 uni-app Vue3
Downloads
9
Maintainers
Readme
wechat-si-recognition
微信小程序「同声传译」语音识别 Hook,内置录音权限申请与引导,适用于 uni-app Vue3 微信小程序。使用方只需关心业务逻辑与自定义 UI,长按调 start()、松手调 stop(),在 onStop 中取 payload.result 即可。
特性
- 仅微信小程序有效,依赖微信官方 同声传译插件
- 内置录音权限:
start()内自动执行「查权 → 申请 → 失败时弹窗引导去设置」 - 非小程序端安全降级:
isAvailable === false,start()返回Promise.resolve(false)
安装
npm install wechat-si-recognition
# 或 pnpm add wechat-si-recognition
# 或 yarn add wechat-si-recognition配置小程序插件(必须)
在项目 src/manifest.json 的 mp-weixin 中声明同声传译插件,否则插件不可用:
{
"mp-weixin": {
"plugins": {
"WechatSI": {
"version": "0.3.5",
"provider": "wx069ba97219f66d99"
}
}
}
}使用示例
import { useWechatSIRecognition } from 'wechat-si-recognition';
const wechatSI = useWechatSIRecognition({
lang: 'zh_CN',
onStop: (payload) => {
const text = (payload.result || '').trim();
if (text) {
// 业务:如发送文本消息
sendMessage({ type: 'text', content: text });
}
},
onError: (payload) => {
console.error(payload.msg);
// 可选:uni.$u.toast(payload.msg);
}
});
// 在自定义「按住说话」按钮上:
// - touchstart:设 300ms 定时器,到点后调用 wechatSI.start()
// - touchend / touchcancel:调用 wechatSI.stop()
// 长按 300ms 后
wechatSI.start().then((ok) => {
if (ok) {
// 显示录音中 UI、震动等
showRecordingOverlay();
uni.vibrateShort({ type: 'medium' });
}
});
// 松手
wechatSI.stop();API
useWechatSIRecognition(options)
| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| options.lang | string | 'zh_CN' | 识别语言:zh_CN | en_US | zh_HK | sichuanhua |
| options.onRecognize | (result: string) => void | - | 识别中间结果(可选) |
| options.onStop | (payload) => void | - | 结束回调,payload 见下表 |
| options.onError | (payload) => void | - | 错误回调,payload: { retcode, msg } |
| options.permissionModal | object | 见下 | 无权限时弹窗文案,可选 |
onStop(payload) 结构:
| 字段 | 类型 | 说明 | |------|------|------| | result | string | 语音转文字结果(松手后最终结果) | | tempFilePath | string | 录音临时文件路径 | | duration | number | 录音时长(ms) | | fileSize | number | 文件大小 |
permissionModal 默认:
{
title: '需要录音权限',
content: '请授权录音,用于语音识别',
confirmText: '去设置',
cancelText: '取消'
}返回值
| 属性 | 类型 | 说明 | |------|------|------| | start | () => Promise<boolean> | 开始录音;内部先处理权限,成功启动则 resolve(true) | | stop | () => void | 停止录音 | | isAvailable | boolean | 当前环境是否可用(仅小程序且已配置插件时为 true) |
错误码
| retcode | 说明 | |---------|------| | -1 | 同声传译插件不可用或启动失败(未配置插件或非小程序端) | | -2 | 未授权录音(用户拒绝或弹窗后未授权) | | 其他 | 以微信插件返回为准,见 插件文档 |
参考
License
MIT
