Commit 22de2cbc by 岑成威

fix: 插件打包

1 parent 39d90bcb
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
<view v-if="panelVisible" class="audio-demo-mask" @tap="panelVisible = false"> <view v-if="panelVisible" class="audio-demo-mask" @tap="panelVisible = false">
<view class="audio-demo-panel" @tap.stop> <view class="audio-demo-panel" @tap.stop>
<view class="panel-head"> <view class="panel-head">
<text class="panel-title">录音 / WS Demo</text> <text class="panel-title">插件 PCM 双开测试</text>
<text class="panel-status">{{ statusText }}</text> <text class="panel-status">{{ statusText }}</text>
<view class="panel-actions"> <view class="panel-actions">
<text class="act" @tap.stop="clearLogs">清空</text> <text class="act" @tap.stop="clearLogs">清空</text>
...@@ -29,10 +29,12 @@ ...@@ -29,10 +29,12 @@
> >
<text class="log-text">{{ line.text }}</text> <text class="log-text">{{ line.text }}</text>
</view> </view>
<view v-if="!logs.length" class="log-empty">点击悬浮按钮开始:录音 5s → WS 上传</view> <view v-if="!logs.length" class="log-empty">
先「开始接待」,再点「测」:在接待录音不停止的前提下,尝试 gl-pcm-capture 插件再开一路 MIC,采 5s 后上传 WS
</view>
</scroll-view> </scroll-view>
<view class="panel-foot"> <view class="panel-foot">
<text class="hint">日志同步至 uni.$logger 与悬浮「日志」球(若已开启)</text> <text class="hint">接待走 uni-recorder-x→framePool;插件走独立 AudioRecord。理想方案是统一采集层(一路 MIC 分流)</text>
</view> </view>
</view> </view>
</view> </view>
...@@ -42,17 +44,28 @@ ...@@ -42,17 +44,28 @@
<script> <script>
// #ifdef APP-PLUS // #ifdef APP-PLUS
import AudioStreamDemoRunner from '@/utils/audioStream/AudioStreamDemoRunner.js' import RecordService from '@/utils/recordManager/RecordService.js'
import AiChatWsService from '@/utils/aiAssistant/AiChatWsService.js'
import AudioStreamService from '@/utils/audioStream/AudioStreamService.js'
import { concatPcmFrames } from '@/utils/audioStream/pcmUtils.js'
import { demoLog } from '@/utils/audioStream/demoLog.js'
// #endif // #endif
const PLUGIN_DEMO_MS = 5000
const PLUGIN_START_TIMEOUT_MS = 8000
const STATUS_MAP = { const STATUS_MAP = {
idle: '待命', idle: '待命',
connecting: '连接 WS…', connecting: '连接 WS…',
recording: '录音中(5s)', recording: '插件采集中',
uploading: '上传中…', uploading: '上传中…',
done: '完成' done: '完成'
} }
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
export default { export default {
name: 'AudioStreamDemo', name: 'AudioStreamDemo',
data() { data() {
...@@ -61,9 +74,8 @@ export default { ...@@ -61,9 +74,8 @@ export default {
status: 'idle', status: 'idle',
logs: [], logs: [],
scrollIntoView: '', scrollIntoView: '',
// #ifdef APP-PLUS _pluginFrames: [],
runner: null _pluginHandler: null
// #endif
} }
}, },
computed: { computed: {
...@@ -79,19 +91,9 @@ export default { ...@@ -79,19 +91,9 @@ export default {
return STATUS_MAP[this.status] || this.status return STATUS_MAP[this.status] || this.status
} }
}, },
created() {
// #ifdef APP-PLUS
this.runner = new AudioStreamDemoRunner({
onLog: (entry) => this.appendLog(entry),
onStatus: (s) => {
this.status = s
}
})
// #endif
},
beforeDestroy() { beforeDestroy() {
// #ifdef APP-PLUS // #ifdef APP-PLUS
this.runner?.cancel() this._stopPluginCapture()
// #endif // #endif
}, },
methods: { methods: {
...@@ -106,13 +108,163 @@ export default { ...@@ -106,13 +108,163 @@ export default {
}, },
async startDemo() { async startDemo() {
// #ifdef APP-PLUS // #ifdef APP-PLUS
this.appendLog({ level: 'info', text: '[AudioDemo] 点击开始', time: Date.now() }) this._log('info', '=== 插件双开测试:接待 MIC + gl-pcm-capture ===')
const ok = await this.runner.start() this.status = 'connecting'
if (!ok && this.status === 'idle') {
uni.showToast({ title: '启动失败,看日志', icon: 'none' }) const recordService = RecordService.getInstance()
const poolBefore = recordService.getFramePoolStatus()
const receptioning = recordService.isReceptioning()
this._log('info', `接待录音: ${receptioning ? '进行中(uni-recorder-x)' : '未开始'}`)
this._log('info', `framePool(接待分流): ${JSON.stringify(poolBefore)}`)
if (!receptioning) {
this._log('warn', '建议先「开始接待」再测,才能验证双 MIC 是否冲突')
}
if (plus.os.name !== 'Android') {
this._log('warn', 'gl-pcm-capture 当前仅 Android,iOS 请用接待 framePool 路径')
this.status = 'idle'
return
}
const aiWs = AiChatWsService.getInstance()
const ws = aiWs.getClient()
const prevOnMessage = ws.onMessage
ws.onMessage = (data) => {
this._log('info', `服务端 <= ${JSON.stringify(data).slice(0, 240)}`)
prevOnMessage && prevOnMessage(data)
}
this._log('info', '检查 AI WS 连接…')
const connected = await aiWs.ensureConnected()
if (!connected) {
this._log('error', 'WebSocket 连接失败')
ws.onMessage = prevOnMessage
this.status = 'idle'
uni.showToast({ title: 'WS 连接失败', icon: 'none' })
return
}
this.status = 'recording'
this._log('info', '尝试在接待不停止的情况下启动 gl-pcm-capture(第二路 AudioRecord)…')
const stream = AudioStreamService.getInstance()
const pluginOk = await this._startPluginCapture()
if (!pluginOk) {
const err = stream.lastError || ''
if (/not found|未加载|index\.uts/i.test(err)) {
this._log('error', `插件未生效: ${err}`)
this._log('warn', '请重新「制作自定义调试基座」后再运行(标准基座不含本地 UTS 插件)')
} else {
this._log('error', `插件启动失败: ${err || '未知原因'}`)
this._log('info', '若接待进行中失败,可能是双 MIC 冲突;统一采集层应走 framePool')
}
ws.onMessage = prevOnMessage
this.status = 'idle'
uni.showToast({
title: /not found|未加载/i.test(err) ? '请重打自定义基座' : '插件启动失败',
icon: 'none'
})
return
}
this._log('info', `插件已启动,采集 ${PLUGIN_DEMO_MS / 1000}s…`)
await sleep(PLUGIN_DEMO_MS)
const frames = this._stopPluginCapture()
const poolAfter = recordService.getFramePoolStatus()
const stillReceptioning = recordService.isReceptioning()
const pluginBytes = frames.reduce((s, f) => s + (f.byteLength || 0), 0)
this._log('info', `插件采集: ${frames.length} 帧 / ${pluginBytes}B`)
this._log('info', `framePool(采集后): ${JSON.stringify(poolAfter)}`)
this._log('info', `接待录音: ${stillReceptioning ? '仍在进行' : '已中断(可能被插件影响)'}`)
const buffer = concatPcmFrames(frames)
if (!buffer?.byteLength) {
this._log('warn', '插件未收到 PCM 帧(MIC 被占用或权限问题)')
ws.onMessage = prevOnMessage
this.status = 'idle'
uni.showToast({ title: '插件无数据', icon: 'none' })
return
}
this.status = 'uploading'
this._log('info', `上传插件 PCM ${buffer.byteLength}B → WS`)
const startOk = await ws.sendJson({ type: 'audio_start' })
if (!startOk) {
this._log('error', 'audio_start 发送失败')
ws.onMessage = prevOnMessage
this.status = 'idle'
return
}
const sent = await ws.send(buffer)
if (!sent) {
this._log('error', 'PCM 发送失败')
ws.onMessage = prevOnMessage
this.status = 'idle'
return
}
await ws.sendJson({ type: 'audio_end' })
this._log('info', '上传完成,等待服务端响应…')
ws.onMessage = prevOnMessage
this.status = 'done'
// #endif
},
async _startPluginCapture() {
// #ifdef APP-PLUS
const stream = AudioStreamService.getInstance()
if (stream.isRunning) {
this._log('warn', '插件已在运行,先停止再重试')
stream.stop()
}
this._pluginFrames = []
this._pluginHandler = (frame) => {
this._pluginFrames.push(frame)
if (frame.seq % 10 === 0) {
this._log('debug', `插件帧#${frame.seq} ${frame.byteLength}B,累计 ${this._pluginFrames.length} 帧`)
}
}
stream.onChunk(this._pluginHandler)
try {
return await Promise.race([
stream.start({ debugLog: false }),
new Promise((_, reject) => {
setTimeout(() => reject(new Error('插件启动超时')), PLUGIN_START_TIMEOUT_MS)
})
])
} catch (e) {
this._log('error', e.message || String(e))
this._stopPluginCapture()
return false
} }
// #endif // #endif
}, },
_stopPluginCapture() {
// #ifdef APP-PLUS
const stream = AudioStreamService.getInstance()
if (this._pluginHandler) {
stream.offChunk(this._pluginHandler)
this._pluginHandler = null
}
if (stream.isRunning) {
stream.stop()
this._log('info', '已停止插件采集(接待录音未主动停止)')
}
const frames = this._pluginFrames.slice()
this._pluginFrames = []
return frames
// #endif
return []
},
_log(level, msg) {
this.appendLog(demoLog(level, msg))
},
appendLog(entry) { appendLog(entry) {
this.logs.push(entry) this.logs.push(entry)
if (this.logs.length > 300) { if (this.logs.length > 300) {
......
...@@ -127,7 +127,9 @@ ...@@ -127,7 +127,9 @@
</template> </template>
</ErrorOrderPopup> </ErrorOrderPopup>
<!-- #ifdef APP-PLUS --> <!-- #ifdef APP-PLUS -->
<AudioStreamDemo /> <!-- 开发用:验证 gl-pcm-capture 与接待录音双开是否冲突 -->
<AudioStreamDemo v-if="showPcmDemo" />
<AiAssistantBall :visible="showAiAssistant" />
<!-- #endif --> <!-- #endif -->
<FloatLogPanel v-if="showFloatLog" /> <FloatLogPanel v-if="showFloatLog" />
</view> </view>
...@@ -136,6 +138,7 @@ ...@@ -136,6 +138,7 @@
import FloatLogPanel from '@/components/FloatLogPanel/FloatLogPanel.vue' import FloatLogPanel from '@/components/FloatLogPanel/FloatLogPanel.vue'
// #ifdef APP-PLUS // #ifdef APP-PLUS
import AudioStreamDemo from '@/components/AudioStreamDemo/AudioStreamDemo.vue' import AudioStreamDemo from '@/components/AudioStreamDemo/AudioStreamDemo.vue'
import AiAssistantBall from '@/components/AiAssistantBall/AiAssistantBall.vue'
// #endif // #endif
import FloatLogConfig from '@/utils/logger/FloatLogConfig.js' import FloatLogConfig from '@/utils/logger/FloatLogConfig.js'
import ReceptionCenter from './components/ReceptionCenter/index.vue' import ReceptionCenter from './components/ReceptionCenter/index.vue'
...@@ -177,6 +180,7 @@ export default { ...@@ -177,6 +180,7 @@ export default {
FloatLogPanel, FloatLogPanel,
// #ifdef APP-PLUS // #ifdef APP-PLUS
AudioStreamDemo, AudioStreamDemo,
AiAssistantBall,
// #endif // #endif
ReceptionCenter, ReceptionCenter,
StudyCenter, StudyCenter,
...@@ -222,7 +226,17 @@ export default { ...@@ -222,7 +226,17 @@ export default {
type: Boolean, type: Boolean,
default: true default: true
}, },
swiperCustom: Boolean swiperCustom: Boolean,
/** 接待详情页展示 AI 悬浮球 */
showAiAssistant: {
type: Boolean,
default: false
},
/** App 端 PCM 截取测试入口(读接待录音 framePool,与插件无关) */
showPcmDemo: {
type: Boolean,
default: true
}
}, },
data() { data() {
return { return {
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
@start="$refs.customerTypeRef.open()" @start="$refs.customerTypeRef.open()"
ref="home" ref="home"
:id="id" :id="id"
:show-ai-assistant="recording && !!id"
@openStep="openStep" @openStep="openStep"
@backHome="backHome" @backHome="backHome"
finishDoneText="下一步" finishDoneText="下一步"
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
@start="start" @start="start"
ref="home" ref="home"
:id="id" :id="id"
:show-ai-assistant="recording && !!id"
@openStep="openStep" @openStep="openStep"
@backHome="backHome" @backHome="backHome"
@changeTab="changeTab" @changeTab="changeTab"
......
...@@ -32,6 +32,7 @@ offPcmFrame() ...@@ -32,6 +32,7 @@ offPcmFrame()
## 注意 ## 注意
- 仅支持 Android App 自定义基座 / 正式包 - 仅支持 Android App **自定义调试基座** / 正式包(标准基座会报 `gl-pcm-capture not found`)
- 新增或修改 `uni_modules/gl-pcm-capture` 后须重新制作自定义基座
- 需要 `RECORD_AUDIO` 权限 - 需要 `RECORD_AUDIO` 权限
- 与 `MediaRecorder` 同时占用 MIC 时,部分机型可能冲突,后续将统一采集层 - 与接待录音 `uni-recorder-x` 同时占用 MIC 时,部分机型可能冲突;生产环境推荐统一采集层(一路 MIC → framePool)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.RECORD_AUDIO" />
</manifest>
// 平台入口:与 uni-recorder-x 相同,由 index.uts 再导出各端实现
// #ifdef APP-ANDROID
import {
startPcmCapture,
stopPcmCapture,
onPcmFrame,
offPcmFrame
} from './app-android/index.uts'
export {
startPcmCapture,
stopPcmCapture,
onPcmFrame,
offPcmFrame
}
// #endif
export type {
PcmFrameResult,
StartPcmCaptureOptions,
StopPcmCaptureOptions,
StartPcmCaptureSuccess,
StopPcmCaptureSuccess,
PcmCaptureFail
} from './interface.uts'
## 为减小组件包的大小,默认组件包中不包含编辑、latex 公式等扩展功能,需要使用扩展功能的请参考下方的 插件扩展 栏的说明
## 功能介绍
- 全端支持(含 `v3、NVUE`)
- 支持丰富的标签(包括 `table`、`video`、`svg` 等)
- 支持丰富的事件效果(自动预览图片、链接处理等)
- 支持设置占位图(加载中、出错时、预览时)
- 支持锚点跳转、长按复制等丰富功能
- 支持大部分 *html* 实体
- 丰富的插件(关键词搜索、内容编辑、`latex` 公式等)
- 效率高、容错性强且轻量化
查看 [功能介绍](https://jin-yufeng.github.io/mp-html/#/overview/feature) 了解更多
## 使用方法
- `uni_modules` 方式
1. 点击右上角的 `使用 HBuilder X 导入插件` 按钮直接导入项目或点击 `下载插件 ZIP` 按钮下载插件包并解压到项目的 `uni_modules/mp-html` 目录下
2. 在需要使用页面的 `(n)vue` 文件中添加
```html
<!-- 不需要引入,可直接使用 -->
<mp-html :content="html" />
```
```javascript
export default {
data() {
return {
html: '<div>Hello World!</div>'
}
}
}
```
3. 需要更新版本时在 `HBuilder X` 中右键 `uni_modules/mp-html` 目录选择 `从插件市场更新` 即可
- 源码方式
1. 从 [github](https://github.com/jin-yufeng/mp-html/tree/master/dist/uni-app) 或 [gitee](https://gitee.com/jin-yufeng/mp-html/tree/master/dist/uni-app) 下载源码
插件市场的 **非 uni_modules 版本** 无法更新,不建议从插件市场获取
2. 在需要使用页面的 `(n)vue` 文件中添加
```html
<mp-html :content="html" />
```
```javascript
import mpHtml from '@/components/mp-html/mp-html'
export default {
// HBuilderX 2.5.5+ 可以通过 easycom 自动引入
components: {
mpHtml
},
data() {
return {
html: '<div>Hello World!</div>'
}
}
}
```
- npm 方式
1. 在项目根目录下执行
```bash
npm install mp-html
```
2. 在需要使用页面的 `(n)vue` 文件中添加
```html
<mp-html :content="html" />
```
```javascript
import mpHtml from 'mp-html/dist/uni-app/components/mp-html/mp-html'
export default {
// 不可省略
components: {
mpHtml
},
data() {
return {
html: '<div>Hello World!</div>'
}
}
}
```
3. 需要更新版本时执行以下命令即可
```bash
npm update mp-html
```
使用 *cli* 方式运行的项目,通过 *npm* 方式引入时,需要在 *vue.config.js* 中配置 *transpileDependencies*,详情可见 [#330](https://github.com/jin-yufeng/mp-html/issues/330#issuecomment-913617687)
如果在 **nvue** 中使用还要将 `dist/uni-app/static` 目录下的内容拷贝到项目的 `static` 目录下,否则无法运行
查看 [快速开始](https://jin-yufeng.github.io/mp-html/#/overview/quickstart) 了解更多
## 组件属性
| 属性 | 类型 | 默认值 | 说明 |
|:---:|:---:|:---:|---|
| container-style | String | | 容器的样式([2.1.0+](https://jin-yufeng.github.io/mp-html/#/changelog/changelog#v210)) |
| content | String | | 用于渲染的 html 字符串 |
| copy-link | Boolean | true | 是否允许外部链接被点击时自动复制 |
| domain | String | | 主域名(用于链接拼接) |
| error-img | String | | 图片出错时的占位图链接 |
| lazy-load | Boolean | false | 是否开启图片懒加载 |
| loading-img | String | | 图片加载过程中的占位图链接 |
| pause-video | Boolean | true | 是否在播放一个视频时自动暂停其他视频 |
| preview-img | Boolean | true | 是否允许图片被点击时自动预览 |
| scroll-table | Boolean | false | 是否给每个表格添加一个滚动层使其能单独横向滚动 |
| selectable | Boolean | false | 是否开启文本长按复制 |
| set-title | Boolean | true | 是否将 title 标签的内容设置到页面标题 |
| show-img-menu | Boolean | true | 是否允许图片被长按时显示菜单 |
| tag-style | Object | | 设置标签的默认样式 |
| use-anchor | Boolean | false | 是否使用锚点链接 |
查看 [属性](https://jin-yufeng.github.io/mp-html/#/basic/prop) 了解更多
## 组件事件
| 名称 | 触发时机 |
|:---:|---|
| load | dom 树加载完毕时 |
| ready | 图片加载完毕时 |
| error | 发生渲染错误时 |
| imgtap | 图片被点击时 |
| linktap | 链接被点击时 |
| play | 音视频播放时 |
查看 [事件](https://jin-yufeng.github.io/mp-html/#/basic/event) 了解更多
## api
组件实例上提供了一些 `api` 方法可供调用
| 名称 | 作用 |
|:---:|---|
| in | 将锚点跳转的范围限定在一个 scroll-view 内 |
| navigateTo | 锚点跳转 |
| getText | 获取文本内容 |
| getRect | 获取富文本内容的位置和大小 |
| setContent | 设置富文本内容 |
| imgList | 获取所有图片的数组 |
| pauseMedia | 暂停播放音视频([2.2.2+](https://jin-yufeng.github.io/mp-html/#/changelog/changelog#v222)) |
| setPlaybackRate | 设置音视频播放速率([2.4.0+](https://jin-yufeng.github.io/mp-html/#/changelog/changelog#v240)) |
查看 [api](https://jin-yufeng.github.io/mp-html/#/advanced/api) 了解更多
## 插件扩展
除基本功能外,本组件还提供了丰富的扩展,可按照需要选用
| 名称 | 作用 |
|:---:|---|
| audio | 音乐播放器 |
| editable | 富文本 **编辑**([示例项目](https://mp-html.oss-cn-hangzhou.aliyuncs.com/editable.zip)) |
| emoji | 解析 emoji |
| highlight | 代码块高亮显示 |
| markdown | 渲染 markdown |
| search | 关键词搜索 |
| style | 匹配 style 标签中的样式 |
| txv-video | 使用腾讯视频 |
| img-cache | 图片缓存 by [@PentaTea](https://github.com/PentaTea) |
| latex | 渲染 latex 公式 by [@Zeng-J](https://github.com/Zeng-J) |
从插件市场导入的包中 **不含有** 扩展插件,使用插件需通过微信小程序 `富文本插件` 获取或参考以下方法进行打包:
1. 获取完整组件包
```bash
npm install mp-html
```
2. 编辑 `tools/config.js` 中的 `plugins` 项,选择需要的插件
3. 生成新的组件包
在 `node_modules/mp-html` 目录下执行
```bash
npm install
npm run build:uni-app
```
4. 拷贝 `dist/uni-app` 中的内容到项目根目录
查看 [插件](https://jin-yufeng.github.io/mp-html/#/advanced/plugin) 了解更多
## 关于 nvue
`nvue` 使用原生渲染,不支持部分 `css` 样式,为实现和 `html` 相同的效果,组件内部通过 `web-view` 进行渲染,性能上差于原生,根据 `weex` 官方建议,`web` 标签仅应用在非常规的降级场景。因此,如果通过原生的方式(如 `richtext`)能够满足需要,则不建议使用本组件,如果有较多的富文本内容,则可以直接使用 `vue` 页面
由于渲染方式与其他端不同,有以下限制:
1. 不支持 `lazy-load` 属性
2. 视频不支持全屏播放
3. 如果在 `flex-direction: row` 的容器中使用,需要给组件设置宽度或设置 `flex: 1` 占满剩余宽度
纯 `nvue` 模式下,[此问题](https://ask.dcloud.net.cn/question/119678) 修复前,不支持通过 `uni_modules` 引入,需要本地引入(将 [dist/uni-app](https://github.com/jin-yufeng/mp-html/tree/master/dist/uni-app) 中的内容拷贝到项目根目录下)
## 问题反馈
遇到问题时,请先查阅 [常见问题](https://jin-yufeng.github.io/mp-html/#/question/faq) 和 [issue](https://github.com/jin-yufeng/mp-html/issues) 中是否已有相同的问题
可通过 [issue](https://github.com/jin-yufeng/mp-html/issues/new/choose) 、插件问答或发送邮件到 [mp_html@126.com](mailto:mp_html@126.com) 提问,不建议在评论区提问(不方便回复)
提问请严格按照 [issue 模板](https://github.com/jin-yufeng/mp-html/issues/new/choose) ,描述清楚使用环境、`html` 内容或可复现的 `demo` 项目以及复现方式,对于 **描述不清**、**无法复现** 或重复的问题将不予回复
欢迎加入 `QQ` 交流群:
群1(已满):`699734691`
群2(已满):`778239129`
群3:`960265313`
查看 [问题反馈](https://jin-yufeng.github.io/mp-html/#/question/feedback) 了解更多
// marked v16+ 依赖 at(),App 端部分 JS 引擎未实现
if (!String.prototype.at) {
// eslint-disable-next-line no-extend-native
String.prototype.at = function (index) {
index = Math.trunc(index) || 0
if (index < 0) index += this.length
if (index < 0 || index >= this.length) return undefined
return this.charAt(index)
}
}
if (!Array.prototype.at) {
// eslint-disable-next-line no-extend-native
Array.prototype.at = function (index) {
index = Math.trunc(index) || 0
if (index < 0) index += this.length
if (index < 0 || index >= this.length) return undefined
return this[index]
}
}
/**
* @fileoverview markdown 插件
* Include marked (https://github.com/markedjs/marked)
* Include github-markdown-css (https://github.com/sindresorhus/github-markdown-css)
*/
import './at-polyfill.js'
import { marked } from './marked.min'
let index = 0
function Markdown (vm) {
this.vm = vm
vm._ids = {}
}
Markdown.prototype.onUpdate = function (content) {
if (this.vm.markdown) {
// 解决中文标点符号后粗体失效的问题,增加零宽空格
content = content.replace(/\*\*([^*]+)\*\*([,。!?;:])/g, '**$1**&#8203;$2')
return marked(content)
}
}
Markdown.prototype.onParse = function (node, vm) {
if (vm.options.markdown) {
// 中文 id 需要转换,否则无法跳转
if (vm.options.useAnchor && node.attrs && /[\u4e00-\u9fa5]/.test(node.attrs.id)) {
const id = 't' + index++
this.vm._ids[node.attrs.id] = id
node.attrs.id = id
}
if (node.name === 'p' || node.name === 'table' || node.name === 'tr' || node.name === 'th' || node.name === 'td' || node.name === 'blockquote' || node.name === 'pre' || node.name === 'code') {
node.attrs.class = `md-${node.name} ${node.attrs.class || ''}`
}
}
}
export default Markdown
{
"id": "mp-html",
"displayName": "mp-html 富文本组件【全端支持,支持编辑、latex等扩展】",
"version": "v2.5.2",
"description": "一个强大的富文本组件,高效轻量,功能丰富",
"keywords": [
"富文本",
"编辑器",
"html",
"rich-text",
"editor"
],
"repository": "https://github.com/jin-yufeng/mp-html",
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/mp-html",
"type": "component-vue",
"darkmode": "x",
"i18n": "x",
"widescreen": "x"
},
"uni_modules": {
"platforms": {
"cloud": {
"tcb": "√",
"aliyun": "√",
"alipay": "x"
},
"client": {
"uni-app": {
"vue": {
"vue2": "√",
"vue3": "√"
},
"web": {
"safari": "√",
"chrome": "√"
},
"app": {
"vue": "√",
"nvue": "√",
"android": "√",
"ios": "√",
"harmony": "-"
},
"mp": {
"weixin": "√",
"alipay": "√",
"toutiao": "-",
"baidu": "√",
"kuaishou": "-",
"jd": "-",
"harmony": "-",
"qq": "√",
"lark": "√"
},
"quickapp": {
"huawei": "-",
"union": "-"
}
},
"uni-app-x": {
"web": {
"safari": "-",
"chrome": "-"
},
"app": {
"android": "-",
"ios": "-",
"harmony": "-"
},
"mp": {
"weixin": "-"
}
}
}
}
},
"engines": {
"HBuilderX": "^3.1.0",
"uni-app": "^3.6.15",
"uni-app-x": ""
}
}
\ No newline at end of file \ No newline at end of file
"use strict";function t(t){for(var e=Object.create(null),n=t.attributes.length;n--;)e[t.attributes[n].name]=t.attributes[n].value;return e}function e(){a[1]&&(this.src=a[1],this.onerror=null),this.onclick=null,this.ontouchstart=null,uni.postMessage({data:{action:"onError",source:"img",attrs:t(this)}})}function n(){window.unloadimgs-=1,0===window.unloadimgs&&uni.postMessage({data:{action:"onReady"}})}function o(r,s,c){for(var d=0;d<r.length;d++)!function(){var u,l=r[d];if(l.type&&"node"!==l.type)u=document.createTextNode(l.text.replace(/&amp;/g,"&"));else{var g=l.name;"svg"===g&&(c="http://www.w3.org/2000/svg"),"html"!==g&&"body"!==g||(g="div"),u=c?document.createElementNS(c,g):document.createElement(g);for(var p in l.attrs)u.setAttribute(p,l.attrs[p]);if(l.children&&o(l.children,u,c),"img"===g){if(window.unloadimgs+=1,u.onload=n,u.onerror=n,!u.src&&u.getAttribute("data-src")&&(u.src=u.getAttribute("data-src")),l.attrs.ignore||(u.onclick=function(e){e.stopPropagation(),uni.postMessage({data:{action:"onImgTap",attrs:t(this)}})}),a[2]){var h=new Image;h.src=u.src,u.src=a[2],h.onload=function(){u.src=this.src},h.onerror=function(){u.onerror()}}u.onerror=e}else if("a"===g)u.addEventListener("click",function(e){e.stopPropagation(),e.preventDefault();var n,o=this.getAttribute("href");o&&"#"===o[0]&&(n=(document.getElementById(o.substr(1))||{}).offsetTop),uni.postMessage({data:{action:"onLinkTap",attrs:t(this),offset:n}})},!0);else if("video"===g||"audio"===g)i.push(u),l.attrs.autoplay||l.attrs.controls||u.setAttribute("controls","true"),u.onplay=function(){if(uni.postMessage({data:{action:"onPlay"}}),a[3])for(var t=0;t<i.length;t++)i[t]!==this&&i[t].pause()},u.onerror=function(){uni.postMessage({data:{action:"onError",source:g,attrs:t(this)}})};else if("table"===g&&a[4]&&!u.style.cssText.includes("inline")){var f=document.createElement("div");f.style.overflow="auto",f.appendChild(u),u=f}else"svg"===g&&(c=void 0)}s.appendChild(u)}()}document.addEventListener("UniAppJSBridgeReady",function(){document.body.onclick=function(){return uni.postMessage({data:{action:"onClick"}})},uni.postMessage({data:{action:"onJSBridgeReady"}})});var a,i=[];window.setContent=function(t,e,n){var r=document.getElementById("content");e[0]&&(document.body.style.cssText=e[0]),e[5]||(r.style.userSelect="none"),n||(r.innerHTML="",i=[]),a=e,window.unloadimgs=0;var s=document.createDocumentFragment();o(t,s),r.appendChild(s);var c=r.scrollHeight;uni.postMessage({data:{action:"onLoad",height:c}}),window.unloadimgs||uni.postMessage({data:{action:"onReady",height:c}}),clearInterval(window.timer),window.timer=setInterval(function(){r.scrollHeight!==c&&(c=r.scrollHeight,uni.postMessage({data:{action:"onHeightChange",height:c}}))},350)},window.onunload=function(){clearInterval(window.timer)};
\ No newline at end of file \ No newline at end of file
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e=e||self).uni=n()}(this,(function(){"use strict";try{var e={};Object.defineProperty(e,"passive",{get:function(){!0}}),window.addEventListener("test-passive",null,e)}catch(e){}var n=Object.prototype.hasOwnProperty;function t(e,t){return n.call(e,t)}var i=[],a=function(e,n){var t={options:{timestamp:+new Date},name:e,arg:n};if(window.__dcloud_weex_postMessage||window.__dcloud_weex_){if("postMessage"===e){var a={data:[n]};return window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(a):window.__dcloud_weex_.postMessage(JSON.stringify(a))}var o={type:"WEB_INVOKE_APPSERVICE",args:{data:t,webviewIds:i}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(o):window.__dcloud_weex_.postMessageToService(JSON.stringify(o))}if(!window.plus)return window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:t,pageId:""},"*");if(0===i.length){var r=plus.webview.currentWebview();if(!r)throw new Error("plus.webview.currentWebview() is undefined");var d=r.parent(),s="";s=d?d.id:r.id,i.push(s)}if(plus.webview.getWebviewById("__uniapp__service"))plus.webview.postMessageToUniNView({type:"WEB_INVOKE_APPSERVICE",args:{data:t,webviewIds:i}},"__uniapp__service");else{var w=JSON.stringify(t);plus.webview.getLaunchWebview().evalJS('UniPlusBridge.subscribeHandler("'.concat("WEB_INVOKE_APPSERVICE",'",').concat(w,",").concat(JSON.stringify(i),");"))}},o={navigateTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("navigateTo",{url:encodeURI(n)})},navigateBack:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.delta;a("navigateBack",{delta:parseInt(n)||1})},switchTab:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("switchTab",{url:encodeURI(n)})},reLaunch:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("reLaunch",{url:encodeURI(n)})},redirectTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("redirectTo",{url:encodeURI(n)})},getEnv:function(e){window.plus?e({plus:!0}):e({h5:!0})},postMessage:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};a("postMessage",e.data||{})}},r=/uni-app/i.test(navigator.userAgent),d=/Html5Plus/i.test(navigator.userAgent),s=/complete|loaded|interactive/;var w=window.my&&navigator.userAgent.indexOf("AlipayClient")>-1;var u=window.swan&&window.swan.webView&&/swan/i.test(navigator.userAgent);var c=window.qq&&window.qq.miniProgram&&/QQ/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var g=window.tt&&window.tt.miniProgram&&/toutiaomicroapp/i.test(navigator.userAgent);var v=window.wx&&window.wx.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var p=window.qa&&/quickapp/i.test(navigator.userAgent);for(var l,_=function(){window.UniAppJSBridge=!0,document.dispatchEvent(new CustomEvent("UniAppJSBridgeReady",{bubbles:!0,cancelable:!0}))},f=[function(e){if(r||d)return window.__dcloud_weex_postMessage||window.__dcloud_weex_?document.addEventListener("DOMContentLoaded",e):window.plus&&s.test(document.readyState)?setTimeout(e,0):document.addEventListener("plusready",e),o},function(e){if(v)return window.WeixinJSBridge&&window.WeixinJSBridge.invoke?setTimeout(e,0):document.addEventListener("WeixinJSBridgeReady",e),window.wx.miniProgram},function(e){if(c)return window.QQJSBridge&&window.QQJSBridge.invoke?setTimeout(e,0):document.addEventListener("QQJSBridgeReady",e),window.qq.miniProgram},function(e){if(w){document.addEventListener("DOMContentLoaded",e);var n=window.my;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){if(u)return document.addEventListener("DOMContentLoaded",e),window.swan.webView},function(e){if(g)return document.addEventListener("DOMContentLoaded",e),window.tt.miniProgram},function(e){if(p){window.QaJSBridge&&window.QaJSBridge.invoke?setTimeout(e,0):document.addEventListener("QaJSBridgeReady",e);var n=window.qa;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){return document.addEventListener("DOMContentLoaded",e),o}],m=0;m<f.length&&!(l=f[m](_));m++);l||(l={});var E="undefined"!=typeof uni?uni:{};if(!E.navigateTo)for(var b in l)t(l,b)&&(E[b]=l[b]);return E.webView=l,E}));
\ No newline at end of file \ No newline at end of file
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"><style>body,html{width:100%;height:100%;overflow-x:scroll;overflow-y:hidden}body{margin:0}video{width:300px;height:225px}img{max-width:100%;-webkit-touch-callout:none}</style></head><body><div id="content" style="overflow:hidden"></div><script type="text/javascript" src="./js/uni.webview.min.js"></script><script type="text/javascript" src="./js/handler.js"></script></body>
\ No newline at end of file \ No newline at end of file
const SKIP_MENU_KEY = 'ai_assistant_skip_menu'
const GUIDE_DATE_KEY = 'ai_assistant_guide_date'
function todayKey() {
const d = new Date()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${d.getFullYear()}-${m}-${day}`
}
export function getSkipMenu() {
return !!uni.getStorageSync(SKIP_MENU_KEY)
}
export function setSkipMenu(value) {
uni.setStorageSync(SKIP_MENU_KEY, !!value)
}
/** 是否应在今日展示引导气泡(每天首次) */
export function shouldShowDailyGuide() {
const last = uni.getStorageSync(GUIDE_DATE_KEY)
return last !== todayKey()
}
export function markDailyGuideShown() {
uni.setStorageSync(GUIDE_DATE_KEY, todayKey())
}
/*
* 接待场景 AI 对话 WebSocket(跟随接待会话建连/断连)
*/
import NativeWsClient from '@/utils/socket/NativeWsClient.js'
import { AUDIO_CHAT_WS_URL } from '@/utils/socket/wsConfig.js'
class AiChatWsService {
static _instance = null
constructor() {
this._connectPromise = null
/** 是否由接待会话托管(仅此种情况在 stopAudio 时断开) */
this._receptionBound = false
}
static getInstance() {
if (!AiChatWsService._instance) {
AiChatWsService._instance = new AiChatWsService()
}
return AiChatWsService._instance
}
getClient() {
return NativeWsClient.getInstance()
}
isConnected() {
return this.getClient().isConnected
}
/**
* 建立 AI 对话 WS
* @param {{ fromReception?: boolean }} [options] fromReception=true 时跟随接待生命周期断连
*/
connectForReception(options = {}) {
// #ifndef APP-PLUS
return Promise.resolve(false)
// #endif
// #ifdef APP-PLUS
if (options.fromReception) {
this._receptionBound = true
}
if (this.isConnected()) {
return Promise.resolve(true)
}
if (this._connectPromise) {
return this._connectPromise
}
this._connectPromise = (async () => {
try {
uni.$logger?.local?.info(`[AiChatWs] 接待开始,连接 ${AUDIO_CHAT_WS_URL}`)
await this.getClient().connectDirect(AUDIO_CHAT_WS_URL)
return true
} catch (e) {
uni.$logger?.local?.warn(`[AiChatWs] 连接失败: ${e.message || e}`)
return false
} finally {
this._connectPromise = null
}
})()
return this._connectPromise
// #endif
}
/** 结束接待:断开并停止自动重连 */
async disconnectReception() {
// #ifndef APP-PLUS
return
// #endif
// #ifdef APP-PLUS
if (!this._receptionBound) {
return
}
this._receptionBound = false
this._connectPromise = null
const client = this.getClient()
try {
uni.$logger?.local?.info('[AiChatWs] 接待结束,断开 WS')
await client.close(1000, 'reception end', true)
} catch (e) {
uni.$logger?.local?.warn(`[AiChatWs] 断开异常: ${e.message || e}`)
}
// #endif
}
/** 求助前确保已连接(接待开始时通常已连好,此处作兜底) */
async ensureConnected() {
if (this.isConnected()) {
return true
}
return this.connectForReception()
}
}
export default AiChatWsService
import { DEMO_STREAM_MARKDOWN } from './demoStreamMarkdown.js'
import {
USE_AI_STREAM_MOCK,
STREAM_MOCK_CHARS_PER_TICK,
STREAM_MOCK_INTERVAL_MS,
STREAM_WAIT_TIMEOUT_MS
} from './constants.js'
import AiChatWsService from './AiChatWsService.js'
const STREAM_DELTA_TYPES = new Set([
'text',
'delta',
'chunk',
'markdown',
'content',
'message',
'answer'
])
const STREAM_DONE_TYPES = new Set(['done', 'end', 'complete', 'finished', 'stop'])
function extractDelta(data) {
if (!data || typeof data !== 'object') return ''
if (STREAM_DONE_TYPES.has(data.type)) return null
if (data.type === 'receiving' || data.type === 'processing') return ''
if (STREAM_DELTA_TYPES.has(data.type)) {
return data.content ?? data.text ?? data.delta ?? data.markdown ?? data.message ?? ''
}
if (typeof data.content === 'string' && data.type !== 'error') {
return data.content
}
return ''
}
function isDoneMessage(data) {
return data && STREAM_DONE_TYPES.has(data.type)
}
function isErrorMessage(data) {
return data && (data.type === 'error' || data.error)
}
class AiStreamSession {
constructor() {
this._active = false
this._markdown = ''
this._callbacks = null
this._prevOnMessage = null
this._mockTimer = null
this._timeoutTimer = null
this._mockIndex = 0
this._useMock = false
}
get isActive() {
return this._active
}
get markdown() {
return this._markdown
}
/**
* @param {{ onUpdate?: Function, onDone?: Function, onError?: Function, useMock?: boolean }} callbacks
*/
start(callbacks = {}) {
this.cancel()
this._active = true
this._markdown = ''
this._callbacks = callbacks
this._useMock = callbacks.useMock ?? USE_AI_STREAM_MOCK
if (this._useMock) {
this._startMockStream(DEMO_STREAM_MARKDOWN)
} else {
this._bindWsListener()
this._timeoutTimer = setTimeout(() => {
if (this._active) {
this._finish(new Error('等待 AI 回复超时'))
}
}, STREAM_WAIT_TIMEOUT_MS)
}
return this
}
cancel() {
this._active = false
this._unbindWsListener()
this._clearTimers()
this._callbacks = null
this._mockIndex = 0
}
handleWsMessage(data) {
if (!this._active) return
if (isErrorMessage(data)) {
const msg = data.message || data.content || data.error || 'AI 返回错误'
this._finish(new Error(msg))
return
}
if (isDoneMessage(data)) {
this._finish()
return
}
const delta = extractDelta(data)
if (delta === null) {
this._finish()
return
}
if (delta) {
this._append(delta)
}
}
_append(chunk) {
if (!chunk) return
this._markdown += chunk
this._callbacks?.onUpdate?.({
markdown: this._markdown,
delta: chunk
})
}
_finish(err) {
if (!this._active) return
this._active = false
this._clearTimers()
this._unbindWsListener()
if (err) {
this._callbacks?.onError?.(err)
} else {
this._callbacks?.onDone?.({
markdown: this._markdown
})
}
this._callbacks = null
}
_bindWsListener() {
const client = AiChatWsService.getInstance().getClient()
this._prevOnMessage = client.onMessage
client.onMessage = (data) => {
this.handleWsMessage(data)
this._prevOnMessage && this._prevOnMessage(data)
}
}
_unbindWsListener() {
const client = AiChatWsService.getInstance().getClient()
if (client.onMessage && this._prevOnMessage !== undefined) {
client.onMessage = this._prevOnMessage
}
this._prevOnMessage = null
}
_clearTimers() {
if (this._mockTimer) {
clearInterval(this._mockTimer)
this._mockTimer = null
}
if (this._timeoutTimer) {
clearTimeout(this._timeoutTimer)
this._timeoutTimer = null
}
}
_startMockStream(fullText) {
this._mockIndex = 0
this._mockTimer = setInterval(() => {
if (!this._active) return
if (this._mockIndex >= fullText.length) {
this._finish()
return
}
const chunk = fullText.slice(this._mockIndex, this._mockIndex + STREAM_MOCK_CHARS_PER_TICK)
this._mockIndex += STREAM_MOCK_CHARS_PER_TICK
this._append(chunk)
}, STREAM_MOCK_INTERVAL_MS)
}
}
let _instance = null
export function getAiStreamSession() {
if (!_instance) {
_instance = new AiStreamSession()
}
return _instance
}
export default AiStreamSession
/** true:音频仍走真实 WS 上传,回复用本地 markdown 模拟流式输出;联调通过后改为 false */
export const USE_AI_STREAM_MOCK = true
/** 模拟流式:每 tick 追加字符数(越小越像逐字输出) */
export const STREAM_MOCK_CHARS_PER_TICK = 12
export const STREAM_MOCK_INTERVAL_MS = 25
export const STREAM_WAIT_TIMEOUT_MS = 120000
/**
* 流式渲染演示用 Markdown(iOS __uniConfig 白屏问题记录)
* 联调真实 AI 后可将 USE_AI_STREAM_MOCK 设为 false
*/
export const DEMO_STREAM_MARKDOWN = `# iOS 26.x 切后台白屏(\`__uniConfig\` 丢失)问题记录
> 版本:2.26.6 · 框架:uni-app Vue2 · 设备:iPadOS 26.4+(App Store 审核复现)
> 涉及文件:\`utils/ensureUniConfig.js\`、\`main.js\`、\`App.vue\`
---
## 1. 问题现象
### 触发条件
- App 切到后台一段时间后,再切回前台
- 低版本 iOS 难以复现,**iPadOS 26.4 / 26.5** 高概率出现
- \`pages.json\` 注册路由较多(本项目约 **52 条**)时更容易触发
### 控制台典型日志
\`\`\`
【==== 切出 ====】 APP
(uView、init.js 再次打印,说明 main.js 被重新执行)
ReferenceError: Can't find variable: __uniConfig
TypeError: r[t] is not a function
TypeError: undefined is not an object (evaluating 'r.addVData')
【==== 切回 ====】 APP
(若不处理,页面白屏,业务无法继续)
\`\`\`
### 用户侧表现
- 屏幕空白,无法操作
- 有时底层 WS、SQLite 仍在跑,但页面已无法渲染
---
## 2. 根因分析
| 层级 | 说明 |
|------|------|
| **直接原因** | 切回前台时 uni-app 运行时未正确重新注入 \`__uniConfig\`,或 JS 上下文被整包重跑,内部路由/页面注册对象(\`addVData\`、\`r[t]\`)处于损坏状态 |
| **表现** | \`main.js\`、\`init.js\` 再次执行(与冷启动类似),但引擎状态不完整 |
| **诱因** | iOS 26.x 对 WebView / JS 上下文管理变化 + 路由表过大,使该问题在审核设备上稳定复现 |
| **框架层** | 属于 DCloud 引擎侧问题,业务代码无法「修复注入」,只能 **检测 + 兜底恢复** |
---
## 4. 最终方案
### 4.1 思路
> **不试图在业务层「修好」uni 引擎,而是:可靠检出损坏 → 放弃当前页面栈 → \`reLaunch\` 登录页,让用户重新进入可用状态。**
代价:切回白屏时用户需 **重新登录**;收益:避免无限白屏,通过 App Store 审核。
### 4.2 核心机制
#### (1)损坏检测(多路并行)
\`\`\`
onHide
└─ 写入 ZY_BG_AT(时间戳)+ ZY_WAS_BACKGROUND
main.js 加载时(同进程 JS 重跑)
├─ syncProcessStartupFlags():对比 launchLoadedTime,新进程则清 BG 标记
├─ detectMainJsReEntry():
│ ├─ getApp() 仍能拿到实例 → 损坏
│ └─ ZY_BG_AT 在 2 分钟内 → 损坏(切回核心条件)
└─ ensureUniConfig():__uniConfig 缺失则从 storage 恢复,并标记损坏
\`\`\`
匹配关键字:\`__uniConfig\`、\`addVData\`、\`r[t] is not a function\`
#### (2)粘性恢复标记 \`_recoverRequired\`
一旦判定损坏,置 \`_recoverRequired = true\`:
- **不会因为** 从 backup 恢复了 \`__uniConfig\` 变量就清除
- **不会因为** \`onLaunch\` 里看到 config 存在就清除
- 仅在 \`reLaunch\` 登录页成功后清除
---
## 8. 总结
1. **问题本质**:uni-app 在 iOS 26.x 切回时 JS 上下文异常重建,\`__uniConfig\` 及页面注册体系损坏,导致白屏。
2. **业务无法根治**:备份 \`__uniConfig\` 只能补变量,无法修复引擎内部对象。
3. **有效手段**:\`ZY_BG_AT\` 2 分钟 + \`main.js\` 重跑检测 + \`_recoverRequired\` 粘性标记 + 强制 \`reLaunch\` 登录。
4. **关键踩坑**:切回时 \`onLaunch\` 仍会执行,若在此时因 \`__uniConfig\` 存在就清除损坏标记,会导致 **检测到损坏却不跳转**。
5. **当前状态**:切回白屏可恢复至登录页;杀进程冷启动不误判。方案已在审核设备验证可用。
---
*以上内容由 AI 流式模拟输出,使用 [mp-html](https://ext.dcloud.net.cn/plugin?id=805) 渲染。*
`
...@@ -26,6 +26,11 @@ class AudioStreamService { ...@@ -26,6 +26,11 @@ class AudioStreamService {
this._frameHandler = null this._frameHandler = null
this._logEveryN = 50 this._logEveryN = 50
this._frameCount = 0 this._frameCount = 0
this._lastError = ''
}
get lastError() {
return this._lastError
} }
static getInstance() { static getInstance() {
...@@ -75,9 +80,8 @@ class AudioStreamService { ...@@ -75,9 +80,8 @@ class AudioStreamService {
} }
if (typeof startPcmCapture !== 'function') { if (typeof startPcmCapture !== 'function') {
uni.$logger?.local?.error( this._lastError = 'gl-pcm-capture 未加载(缺少 utssdk/index.uts 或未打自定义基座)'
'[AudioStream] gl-pcm-capture 未加载,请使用含 UTS 插件的自定义基座/正式包' uni.$logger?.local?.error(`[AudioStream] ${this._lastError}`)
)
return Promise.resolve(false) return Promise.resolve(false)
} }
...@@ -85,6 +89,8 @@ class AudioStreamService { ...@@ -85,6 +89,8 @@ class AudioStreamService {
return Promise.resolve(true) return Promise.resolve(true)
} }
this._lastError = ''
const sampleRate = options.sampleRate || DEFAULT_SAMPLE_RATE const sampleRate = options.sampleRate || DEFAULT_SAMPLE_RATE
const frameSize = options.frameSize || DEFAULT_FRAME_SIZE const frameSize = options.frameSize || DEFAULT_FRAME_SIZE
const debugLog = options.debugLog !== false const debugLog = options.debugLog !== false
...@@ -109,22 +115,31 @@ class AudioStreamService { ...@@ -109,22 +115,31 @@ class AudioStreamService {
onPcmFrame(this._frameHandler) onPcmFrame(this._frameHandler)
return new Promise((resolve) => { return new Promise((resolve) => {
startPcmCapture({ try {
sampleRate, startPcmCapture({
frameSize, sampleRate,
success: () => { frameSize,
this._running = true success: () => {
this._frameCount = 0 this._running = true
uni.$logger?.local?.info('[AudioStream] PCM 采集已启动') this._frameCount = 0
resolve(true) uni.$logger?.local?.info('[AudioStream] PCM 采集已启动')
}, resolve(true)
fail: (err) => { },
offPcmFrame() fail: (err) => {
this._frameHandler = null offPcmFrame()
uni.$logger?.local?.error(`[AudioStream] 启动失败: ${JSON.stringify(err)}`) this._frameHandler = null
resolve(false) this._lastError = err?.errMsg || JSON.stringify(err) || 'startPcmCapture fail'
} uni.$logger?.local?.error(`[AudioStream] 启动失败: ${this._lastError}`)
}) resolve(false)
}
})
} catch (e) {
offPcmFrame()
this._frameHandler = null
this._lastError = e?.message || String(e)
uni.$logger?.local?.error(`[AudioStream] 启动异常: ${this._lastError}`)
resolve(false)
}
}) })
// #endif // #endif
} }
......
...@@ -27,3 +27,22 @@ export function normalizePcmFrame(frame) { ...@@ -27,3 +27,22 @@ export function normalizePcmFrame(frame) {
buffer: base64ToArrayBuffer(frame.base64) buffer: base64ToArrayBuffer(frame.base64)
} }
} }
/**
* 合并多帧 PCM 为单个 ArrayBuffer
* @param {Array<{ buffer: ArrayBuffer, byteLength?: number }>} frames
* @returns {ArrayBuffer|null}
*/
export function concatPcmFrames(frames) {
if (!frames?.length) return null
const total = frames.reduce((sum, f) => sum + (f.byteLength || f.buffer?.byteLength || 0), 0)
if (!total) return null
const out = new Uint8Array(total)
let offset = 0
for (const frame of frames) {
const chunk = new Uint8Array(frame.buffer)
out.set(chunk, offset)
offset += chunk.byteLength
}
return out.buffer
}
...@@ -13,6 +13,7 @@ import permission from '@/js_sdk/wa-permission/permission.js' ...@@ -13,6 +13,7 @@ import permission from '@/js_sdk/wa-permission/permission.js'
import store from '@/store' import store from '@/store'
import PathUtils from './PathUtils.js' import PathUtils from './PathUtils.js'
import AudioFramePool from './AudioFramePool.js' import AudioFramePool from './AudioFramePool.js'
import AiChatWsService from '@/utils/aiAssistant/AiChatWsService.js'
class RecordService { class RecordService {
static instance = null static instance = null
...@@ -112,6 +113,7 @@ class RecordService { ...@@ -112,6 +113,7 @@ class RecordService {
} }
this.audioManager.start() this.audioManager.start()
this.timeoutService.start() this.timeoutService.start()
AiChatWsService.getInstance().connectForReception({ fromReception: true })
return true // 返回 true 表示成功启动 return true // 返回 true 表示成功启动
} catch (e) { } catch (e) {
uni.$logger.local.error(`【录音服务RecordService】 == startAudio 异常: ${e.message}\n${e.stack}`) uni.$logger.local.error(`【录音服务RecordService】 == startAudio 异常: ${e.message}\n${e.stack}`)
...@@ -246,6 +248,7 @@ class RecordService { ...@@ -246,6 +248,7 @@ class RecordService {
} }
uni.$logger.local.info('【录音服务RecordService】 == 结束接待! ') uni.$logger.local.info('【录音服务RecordService】 == 结束接待! ')
this.stop() this.stop()
AiChatWsService.getInstance().disconnectReception()
try { try {
await this.saveAndClearRecord(isNotSave) await this.saveAndClearRecord(isNotSave)
} catch (error) { } catch (error) {
......
...@@ -9,6 +9,7 @@ import { loginDevice } from './wsAuth.js' ...@@ -9,6 +9,7 @@ import { loginDevice } from './wsAuth.js'
import { import {
buildAuthenticatedWsUrl, buildAuthenticatedWsUrl,
getNativeWsBase, getNativeWsBase,
normalizeWsUrl,
pickLoginWsUrl pickLoginWsUrl
} from './wsConfig.js' } from './wsConfig.js'
import { normalizeWsPayload } from './wsMessage.js' import { normalizeWsPayload } from './wsMessage.js'
...@@ -37,14 +38,39 @@ class NativeWsClient { ...@@ -37,14 +38,39 @@ class NativeWsClient {
this._reconnectTimer = null this._reconnectTimer = null
this._reconnectCount = 0 this._reconnectCount = 0
this._isReconnecting = false this._isReconnecting = false
this._directUrl = ''
} }
get isConnected() { get isConnected() {
return this._connected && this.socketTask != null return this._connected && this.socketTask != null
} }
/** 直连指定 ws 地址(无登录鉴权,用于音频对话等独立服务) */
async connectDirect(url) {
const target = normalizeWsUrl(url)
if (!target) {
throw new Error('connectDirect 缺少 url')
}
this._manualClose = false
this._directUrl = target
await this.close(1000, 'reconnect', false).catch(() => {})
this._manualClose = false
try {
await this._connectSocketByUrl(target)
} catch (e) {
this._log('error', `connectDirect 失败: ${e.message}`)
throw e
}
}
/** 发送纯 JSON 字符串,不附加 device_id 等字段 */
sendJson(obj) {
return this.send(JSON.stringify(obj))
}
async connect() { async connect() {
this._manualClose = false this._manualClose = false
this._directUrl = ''
try { try {
const loginRes = await loginDevice() const loginRes = await loginDevice()
const code = loginRes?.code const code = loginRes?.code
...@@ -76,14 +102,20 @@ class NativeWsClient { ...@@ -76,14 +102,20 @@ class NativeWsClient {
this._log('warn', '未连接,send 忽略') this._log('warn', '未连接,send 忽略')
return Promise.resolve(false) return Promise.resolve(false)
} }
const packet = let packet
typeof data === 'string' if (typeof data === 'string') {
? data packet = data
: JSON.stringify({ } else if (data instanceof ArrayBuffer) {
...data, packet = data
device_id: this.deviceId, } else if (ArrayBuffer.isView(data)) {
type: data.type || type packet = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)
}) } else {
packet = JSON.stringify({
...data,
device_id: this.deviceId,
type: data.type || type
})
}
return new Promise((resolve) => { return new Promise((resolve) => {
this.socketTask.send({ this.socketTask.send({
data: packet, data: packet,
...@@ -222,7 +254,10 @@ class NativeWsClient { ...@@ -222,7 +254,10 @@ class NativeWsClient {
this._log('warn', `${delay}ms 后第 ${this._reconnectCount} 次重连`) this._log('warn', `${delay}ms 后第 ${this._reconnectCount} 次重连`)
this._reconnectTimer = setTimeout(() => { this._reconnectTimer = setTimeout(() => {
this._reconnectTimer = null this._reconnectTimer = null
this.connect().catch(() => {}) const reconnect = this._directUrl
? () => this.connectDirect(this._directUrl)
: () => this.connect()
reconnect().catch(() => {})
}, delay) }, delay)
} }
......
...@@ -43,6 +43,9 @@ export function normalizeWsUrl(url) { ...@@ -43,6 +43,9 @@ export function normalizeWsUrl(url) {
return trimmed return trimmed
} }
/** 音频对话 WebSocket(无鉴权直连) */
export const AUDIO_CHAT_WS_URL = normalizeWsUrl('http://192.168.1.203:8000/ws/audio/chat')
/** /**
* 从登录 data 中取服务端下发的 ws 地址(若有) * 从登录 data 中取服务端下发的 ws 地址(若有)
* @param {object} data * @param {object} data
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!