Commit 219c6421 by 岑成威

fix: 合并到5.8.3

1 parent 22de2cbc
Showing 41 changed files with 492 additions and 1148 deletions
......@@ -127,8 +127,6 @@
</template>
</ErrorOrderPopup>
<!-- #ifdef APP-PLUS -->
<!-- 开发用:验证 gl-pcm-capture 与接待录音双开是否冲突 -->
<AudioStreamDemo v-if="showPcmDemo" />
<AiAssistantBall :visible="showAiAssistant" />
<!-- #endif -->
<FloatLogPanel v-if="showFloatLog" />
......@@ -137,7 +135,6 @@
<script>
import FloatLogPanel from '@/components/FloatLogPanel/FloatLogPanel.vue'
// #ifdef APP-PLUS
import AudioStreamDemo from '@/components/AudioStreamDemo/AudioStreamDemo.vue'
import AiAssistantBall from '@/components/AiAssistantBall/AiAssistantBall.vue'
// #endif
import FloatLogConfig from '@/utils/logger/FloatLogConfig.js'
......@@ -179,7 +176,6 @@ export default {
components: {
FloatLogPanel,
// #ifdef APP-PLUS
AudioStreamDemo,
AiAssistantBall,
// #endif
ReceptionCenter,
......@@ -231,11 +227,6 @@ export default {
showAiAssistant: {
type: Boolean,
default: false
},
/** App 端 PCM 截取测试入口(读接待录音 framePool,与插件无关) */
showPcmDemo: {
type: Boolean,
default: true
}
},
data() {
......
......@@ -31,7 +31,6 @@
/* 模块配置 */
"modules" : {
"Camera" : {},
"Record" : {},
"VideoPlayer" : {},
"AudioPlayer" : {},
"SQLite" : {},
......@@ -90,6 +89,13 @@
"xhdpi" : "static/96.png",
"xxhdpi" : "static/144.png"
}
},
"plugins" : {
"audio" : {
"mp3" : {
"description" : "Android平台录音支持MP3格式文件"
}
}
}
},
"nativePlugins" : {
......
......@@ -43,10 +43,6 @@ export default {
},
updateCustomerInfo(data){
this.recordService.updateCustomerInfo(data)
},
/** 订阅接待中的实时 PCM 音频帧 */
onAudioStreamChunk(callback) {
return this.recordService?.getAudioStreamService()?.onChunk(callback) || (() => {})
}
}
}
No preview for this file type
## 1.0.0
- Android AudioRecord PCM 实时采集
- 支持 onPcmFrame 帧回调(base64)
{
"id": "gl-pcm-capture",
"displayName": "gl-pcm-capture",
"version": "1.0.0",
"description": "Android PCM 实时采集,通过回调输出音频帧(base64)",
"keywords": ["pcm", "audio", "record", "stream"],
"repository": "",
"engines": {
"HBuilderX": "^3.94"
},
"dcloudext": {
"type": "uts",
"sale": {
"regular": { "price": "0.00" },
"sourcecode": { "price": "0.00" }
},
"contact": { "qq": "" },
"declaration": {
"ads": "无",
"data": "插件不采集任何数据,仅在本地回调 PCM 帧",
"permissions": "android.permission.RECORD_AUDIO"
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": { "tcb": "n", "aliyun": "n" },
"client": {
"Vue": { "vue2": "y", "vue3": "y" },
"App": {
"app-android": { "minVersion": "21" },
"app-ios": "n"
},
"H5-mobile": {
"Safari": "n",
"Android Browser": "n",
"微信浏览器(Android)": "n",
"QQ浏览器(Android)": "n"
},
"H5-pc": {
"Chrome": "n",
"IE": "n",
"Edge": "n",
"Firefox": "n",
"Safari": "n"
},
"小程序": {
"微信": "n",
"阿里": "n",
"百度": "n",
"字节跳动": "n",
"QQ": "n",
"钉钉": "n",
"快手": "n",
"飞书": "n",
"京东": "n"
},
"快应用": { "华为": "n", "联盟": "n" }
}
}
}
}
# gl-pcm-capture
Android 端 PCM 实时采集 UTS 插件。通过 `AudioRecord` 在后台线程读取音频帧,以 base64 形式回调给 JS 层。
## 使用
```javascript
import {
startPcmCapture,
stopPcmCapture,
onPcmFrame,
offPcmFrame
} from '@/uni_modules/gl-pcm-capture'
onPcmFrame((frame) => {
console.log('pcm frame', frame.seq, frame.byteLength)
})
startPcmCapture({
sampleRate: 16000,
frameSize: 4096,
success: () => console.log('started'),
fail: (err) => console.error(err)
})
// 停止
stopPcmCapture()
offPcmFrame()
```
推荐通过 `utils/audioStream/AudioStreamService.js` 封装使用。
## 注意
- 仅支持 Android App **自定义调试基座** / 正式包(标准基座会报 `gl-pcm-capture not found`)
- 新增或修改 `uni_modules/gl-pcm-capture` 后须重新制作自定义基座
- 需要 `RECORD_AUDIO` 权限
- 与接待录音 `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>
package uts.sdk.modules.glPcmCapture
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.util.Base64
/**
* PCM 读帧结果(供 UTS 层回调 JS)
*/
class PcmFrameData(
val base64: String,
val byteLength: Int
)
object PcmCaptureNative {
@JvmStatic
fun getMinBufferSize(sampleRate: Int): Int {
return AudioRecord.getMinBufferSize(
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT
)
}
@JvmStatic
fun createRecorder(sampleRate: Int, bufferSize: Int): AudioRecord {
return AudioRecord(
MediaRecorder.AudioSource.MIC,
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufferSize
)
}
@JvmStatic
fun readFrame(recorder: AudioRecord, frameSize: Int): PcmFrameData? {
val buffer = ByteArray(frameSize)
val readLen = recorder.read(buffer, 0, frameSize)
if (readLen <= 0) {
return null
}
val base64 = Base64.encodeToString(buffer, 0, readLen, Base64.NO_WRAP)
return PcmFrameData(base64, readLen)
}
}
import AudioRecord from 'android.media.AudioRecord'
import Thread from 'java.lang.Thread'
import Runnable from 'java.lang.Runnable'
import { PcmCaptureNative } from 'uts.sdk.modules.glPcmCapture'
import {
StartPcmCaptureOptions,
StartPcmCaptureSuccess,
PcmFrameResult,
StopPcmCaptureOptions,
StopPcmCaptureSuccess
} from '../interface.uts'
import { PcmCaptureFailImpl } from '../unierror.uts'
let audioRecord : AudioRecord | null = null
let captureThread : Thread | null = null
let isRunning = false
let seqCounter : Int = 0
let frameCallback : ((res : PcmFrameResult) => void) | null = null
let currentSampleRate : Int = 16000
let currentFrameSize : Int = 4096
export function onPcmFrame(callback : (res : PcmFrameResult) => void) : void {
frameCallback = callback
}
export function offPcmFrame() : void {
frameCallback = null
}
function dispatchFrame(frame : PcmFrameResult) : void {
const cb = frameCallback
if (cb == null) {
return
}
const activity = UTSAndroid.getUniActivity()
if (activity != null) {
const uiRunnable = new (class implements Runnable {
override run() : void {
cb(frame)
}
})
activity.runOnUiThread(uiRunnable)
} else {
cb(frame)
}
}
export function startPcmCapture(options : StartPcmCaptureOptions) : void {
if (isRunning) {
const err = new PcmCaptureFailImpl(1400003)
options.fail?.(err)
options.complete?.(err)
return
}
const sampleRateInt = (options.sampleRate ?? 16000).toInt()
const frameSizeInt = (options.frameSize ?? 4096).toInt()
currentSampleRate = sampleRateInt
currentFrameSize = frameSizeInt
const minBufferSize = PcmCaptureNative.getMinBufferSize(sampleRateInt)
if (minBufferSize <= 0) {
const err = new PcmCaptureFailImpl(1400001)
options.fail?.(err)
options.complete?.(err)
return
}
const bufferSizeInt = Math.max(minBufferSize, frameSizeInt * 2).toInt()
try {
const recorder = PcmCaptureNative.createRecorder(sampleRateInt, bufferSizeInt)
if (recorder.getState() != AudioRecord.STATE_INITIALIZED) {
recorder.release()
const err = new PcmCaptureFailImpl(1400002)
options.fail?.(err)
options.complete?.(err)
return
}
audioRecord = recorder
isRunning = true
seqCounter = 0
recorder.startRecording()
const runnable = new (class implements Runnable {
override run() : void {
while (isRunning && audioRecord != null) {
const frameData = PcmCaptureNative.readFrame(audioRecord!, currentFrameSize)
if (frameData != null) {
const frame : PcmFrameResult = {
base64: frameData.base64,
byteLength: frameData.byteLength,
seq: seqCounter,
timestamp: Date.now(),
sampleRate: currentSampleRate,
channels: 1,
bitDepth: 16
}
seqCounter++
dispatchFrame(frame)
} else {
// read 返回 0 或负数时短暂让出 CPU,避免空转
Thread.sleep(10)
}
}
}
})
const thread = new Thread(runnable)
captureThread = thread
thread.start()
const success : StartPcmCaptureSuccess = { errMsg: 'startPcmCapture:ok' }
options.success?.(success)
options.complete?.(success)
} catch (e : Exception) {
isRunning = false
audioRecord = null
const err = new PcmCaptureFailImpl(1400001)
err.errMsg = 'startPcmCapture fail: ' + e.message
options.fail?.(err)
options.complete?.(err)
}
}
export function stopPcmCapture(options ?: StopPcmCaptureOptions) : void {
isRunning = false
const recorder = audioRecord
if (recorder != null) {
try {
recorder.stop()
} catch (e : Exception) {
// 录音过短时 stop 可能抛异常,忽略
}
try {
recorder.release()
} catch (e : Exception) {
// ignore
}
audioRecord = null
}
captureThread = null
seqCounter = 0
const success : StopPcmCaptureSuccess = { errMsg: 'stopPcmCapture:ok' }
options?.success?.(success)
options?.complete?.(success)
}
export type PcmFrameResult = {
base64: string
byteLength: number
seq: number
timestamp: number
sampleRate: number
channels: number
bitDepth: number
}
export type StartPcmCaptureOptions = {
sampleRate?: number
frameSize?: number
success?: (res: { errMsg: string }) => void
fail?: (err: { errCode: number; errMsg: string }) => void
complete?: (res: any) => void
}
export type StopPcmCaptureOptions = {
success?: (res: { errMsg: string }) => void
complete?: (res: any) => void
}
export declare function startPcmCapture(options: StartPcmCaptureOptions): void
export declare function stopPcmCapture(options?: StopPcmCaptureOptions): void
export declare function onPcmFrame(callback: (res: PcmFrameResult) => void): void
export declare function offPcmFrame(): void
// 平台入口:与 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'
export type PcmFrameResult = {
base64 : string
byteLength : number
seq : number
timestamp : number
sampleRate : number
channels : number
bitDepth : number
}
export type StartPcmCaptureSuccess = {
errMsg : string
}
export type StopPcmCaptureSuccess = {
errMsg : string
}
export type PcmCaptureErrorCode = 1400001 | 1400002 | 1400003
export interface PcmCaptureFail extends IUniError {
errCode : PcmCaptureErrorCode
}
export type PcmCaptureFailCallback = (err : PcmCaptureFail) => void
export type StartPcmCaptureSuccessCallback = (res : StartPcmCaptureSuccess) => void
export type StopPcmCaptureSuccessCallback = (res : StopPcmCaptureSuccess) => void
export type PcmCaptureCompleteCallback = (res : any) => void
export type PcmFrameCallback = (res : PcmFrameResult) => void
export type StartPcmCaptureOptions = {
sampleRate ?: number
frameSize ?: number
success ?: StartPcmCaptureSuccessCallback | null
fail ?: PcmCaptureFailCallback | null
complete ?: PcmCaptureCompleteCallback | null
}
export type StopPcmCaptureOptions = {
success ?: StopPcmCaptureSuccessCallback | null
fail ?: PcmCaptureFailCallback | null
complete ?: PcmCaptureCompleteCallback | null
}
export type StartPcmCapture = (options : StartPcmCaptureOptions) => void
export type StopPcmCapture = (options ?: StopPcmCaptureOptions) => void
export type OnPcmFrame = (callback : PcmFrameCallback) => void
export type OffPcmFrame = () => void
import { PcmCaptureErrorCode, PcmCaptureFail } from "./interface.uts"
export const UniErrorSubject = 'gl-pcm-capture'
export const UniErrors : Map<PcmCaptureErrorCode, string> = new Map([
[1400001, 'AudioRecord init or read failed'],
[1400002, 'AudioRecord not initialized'],
[1400003, 'Already capturing'],
])
export class PcmCaptureFailImpl extends UniError implements PcmCaptureFail {
constructor(errCode : PcmCaptureErrorCode) {
super()
this.errSubject = UniErrorSubject
this.errCode = errCode
this.errMsg = UniErrors[errCode] ?? ""
}
}
......@@ -10,7 +10,6 @@ import android.media.MediaRecorder
import android.os.Handler
import android.os.Looper
import android.util.Log
import io.dcloud.feature.audio.mp3.SimpleLame
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
......@@ -384,9 +383,18 @@ class AudioRecorder() {
}
private fun initLame() {
val channels = getChannelCount()
SimpleLame.init(sampleRate, channels, sampleRate, bitRate / 1000, 7)
lameInitialized = true
try {
val channels = getChannelCount()
SimpleLameBridge.init(sampleRate, channels, sampleRate, bitRate / 1000, 7)
lameInitialized = true
} catch (e: ClassNotFoundException) {
notifyError(
ERROR_INITIALIZATION_FAILED,
"MP3 模块未集成,请确认 manifest 已勾选 Record 模块或 distribute.plugins.audio.mp3(二选一,勿重复勾选)后重新打基座"
)
} catch (e: Exception) {
notifyError(ERROR_INITIALIZATION_FAILED, "MP3 编码器初始化失败: ${e.message}")
}
}
private fun encodeToMp3(pcmBuffer: ByteArray, pcmSize: Int, outputStream: FileOutputStream?) {
......@@ -406,7 +414,7 @@ class AudioRecorder() {
(pcmBuffer[2 * i + 1].toInt() shl 8)).toShort()
}
// 假设SimpleLame.encode对于单声道,第二个声道参数传null
encodedSize = SimpleLame.encode(shortBuffer, shortBuffer, sampleCount, mp3Buffer)
encodedSize = SimpleLameBridge.encode(shortBuffer, shortBuffer, sampleCount, mp3Buffer)
} else {
// 立体声处理
// 每个采样点占用4字节(左右声道各2字节),所以采样点数是 pcmSize / 4
......@@ -423,7 +431,7 @@ class AudioRecorder() {
rightChannel[i] = ((pcmBuffer[4 * i + 2].toInt() and 0xFF) or
(pcmBuffer[4 * i + 3].toInt() shl 8)).toShort()
}
encodedSize = SimpleLame.encode(leftChannel, rightChannel, sampleCount, mp3Buffer)
encodedSize = SimpleLameBridge.encode(leftChannel, rightChannel, sampleCount, mp3Buffer)
}
if (encodedSize > 0) {
......@@ -515,7 +523,7 @@ class AudioRecorder() {
if (lameInitialized) {
try {
val mp3Buffer = ByteArray(7200)
val encodedSize = SimpleLame.flush(mp3Buffer)
val encodedSize = SimpleLameBridge.flush(mp3Buffer)
if (encodedSize > 0) {
FileOutputStream(filePath, true).use {
it.write(
......@@ -528,7 +536,7 @@ class AudioRecorder() {
} catch (e: IOException) {
notifyError(ERROR_FILE_WRITE_FAILED, "MP3 flush failed: ${e.message}")
} finally {
SimpleLame.close()
SimpleLameBridge.close()
lameInitialized = false
}
}
......@@ -561,7 +569,7 @@ class AudioRecorder() {
audioRecord = null
if (lameInitialized) {
SimpleLame.close()
SimpleLameBridge.close()
lameInitialized = false
}
audioBuffer = null
......
package uts.sdk.modules.uniRecorder
import android.util.Log
/**
* 运行时由 manifest plugins.audio.mp3 注入 SimpleLame;
* 编译期不 import、不打包 audio-mp3aac aar,避免 Dex 重复。
*/
object SimpleLameBridge {
private const val TAG = "SimpleLameBridge"
private const val CLASS_NAME = "io.dcloud.feature.audio.mp3.SimpleLame"
private var lameClass: Class<*>? = null
private fun clazz(): Class<*> {
if (lameClass == null) {
lameClass = Class.forName(CLASS_NAME)
}
return lameClass!!
}
fun init(inSampleRate: Int, channelCount: Int, outSampleRate: Int, bitrateKbps: Int, quality: Int) {
val method = clazz().getMethod(
"init",
Int::class.javaPrimitiveType,
Int::class.javaPrimitiveType,
Int::class.javaPrimitiveType,
Int::class.javaPrimitiveType,
Int::class.javaPrimitiveType
)
method.invoke(null, inSampleRate, channelCount, outSampleRate, bitrateKbps, quality)
}
fun encode(bufferL: ShortArray, bufferR: ShortArray, samples: Int, mp3buf: ByteArray): Int {
val method = clazz().getMethod(
"encode",
ShortArray::class.java,
ShortArray::class.java,
Int::class.javaPrimitiveType,
ByteArray::class.java
)
return method.invoke(null, bufferL, bufferR, samples, mp3buf) as Int
}
fun flush(mp3buf: ByteArray): Int {
val method = clazz().getMethod("flush", ByteArray::class.java)
return method.invoke(null, mp3buf) as Int
}
fun close() {
try {
val method = clazz().getMethod("close")
method.invoke(null)
} catch (e: Exception) {
Log.w(TAG, "SimpleLame.close failed: ${e.message}")
}
}
}
{}
\ No newline at end of file
{
"minSdkVersion": "21"
}
......@@ -2,7 +2,7 @@
* 接待场景 AI 对话 WebSocket(跟随接待会话建连/断连)
*/
import NativeWsClient from '@/utils/socket/NativeWsClient.js'
import { AUDIO_CHAT_WS_URL } from '@/utils/socket/wsConfig.js'
import { getNativeWsBase } from '@/utils/socket'
class AiChatWsService {
static _instance = null
......@@ -11,6 +11,8 @@ class AiChatWsService {
this._connectPromise = null
/** 是否由接待会话托管(仅此种情况在 stopAudio 时断开) */
this._receptionBound = false
/** 只有明确配置了该 url 才会发起 WebSocket 连接 */
this._wsUrl = ''
}
static getInstance() {
......@@ -24,6 +26,11 @@ class AiChatWsService {
return NativeWsClient.getInstance()
}
/** 显式设置 AI 对话 WS 地址;未设置时不会自动连接 */
setWsUrl(url) {
this._wsUrl = url || ''
}
isConnected() {
return this.getClient().isConnected
}
......@@ -38,6 +45,11 @@ class AiChatWsService {
// #endif
// #ifdef APP-PLUS
const wsUrl = (getNativeWsBase() || '').trim()
if (!wsUrl) {
// 未配置 WS 地址时直接跳过(本项目可纯 HTTP 模式运行)
return Promise.resolve(false)
}
if (options.fromReception) {
this._receptionBound = true
}
......@@ -50,8 +62,8 @@ class AiChatWsService {
this._connectPromise = (async () => {
try {
uni.$logger?.local?.info(`[AiChatWs] 接待开始,连接 ${AUDIO_CHAT_WS_URL}`)
await this.getClient().connectDirect(AUDIO_CHAT_WS_URL)
uni.$logger?.local?.info(`[AiChatWs] 接待开始,连接 ${wsUrl}`)
await this.getClient().connectDirect(wsUrl)
return true
} catch (e) {
uni.$logger?.local?.warn(`[AiChatWs] 连接失败: ${e.message || e}`)
......
/*
* @Description: 首页录音 + WebSocket 边录边传 Demo(NativeWsClient)
*/
import AudioStreamService from './AudioStreamService.js'
import { demoLog } from './demoLog.js'
import NativeWsClient from '@/utils/socket/NativeWsClient.js'
import permision from '@/js_sdk/wa-permission/permission.js'
const DEMO_RECORD_MS = 5000
const PCM_START_TIMEOUT_MS = 8000
export default class AudioStreamDemoRunner {
constructor(hooks = {}) {
this._onLog = hooks.onLog || (() => {})
this._onStatus = hooks.onStatus || (() => {})
this._frames = []
this._chunkHandler = null
this._timer = null
this._running = false
this._ws = null
this._prevOnMessage = null
this._ownsWs = false
this._streamStarted = false
this._sentCount = 0
this._sendChain = Promise.resolve()
}
get isRunning() {
return this._running
}
async start() {
// #ifndef APP-PLUS
this._log('warn', '仅 App 端支持')
return false
// #endif
// #ifdef APP-PLUS
if (this._running) {
this._log('warn', 'Demo 进行中')
return false
}
if (plus.os.name !== 'Android') {
this._log('warn', '当前 Demo 仅支持 Android PCM')
return false
}
const permitted = await this._ensureRecordPermission()
if (!permitted) {
this._log('error', '无录音权限')
return false
}
this._running = true
this._frames = []
this._streamStarted = false
this._sentCount = 0
this._sendChain = Promise.resolve()
this._setStatus('connecting')
this._ws = NativeWsClient.getInstance()
this._prevOnMessage = this._ws.onMessage
this._ws.onMessage = (data) => {
this._log('info', `[WS] 收到 <= ${JSON.stringify(data || {}).slice(0, 240)}`)
this._prevOnMessage && this._prevOnMessage(data)
}
if (!this._ws.isConnected) {
this._log('info', '连接原生 WebSocket(uni.connectSocket)…')
try {
await this._ws.connect()
this._ownsWs = true
} catch (e) {
this._log('error', `WebSocket 连接失败: ${e.message || e}`)
this._cleanup(false)
return false
}
} else {
this._log('info', '复用已有 NativeWs 连接')
}
const stream = AudioStreamService.getInstance()
if (stream.isRunning) {
this._log('warn', 'PCM 采集中(可能接待录音占用麦克风),先停止再试')
stream.stop()
}
this._chunkHandler = (frame) => this._onPcmChunk(frame)
stream.onChunk(this._chunkHandler)
let started = false
try {
started = await Promise.race([
stream.start({ debugLog: true }),
new Promise((_, reject) => {
setTimeout(() => reject(new Error('PCM 启动超时,检查 gl-pcm-capture 插件与麦克风占用')), PCM_START_TIMEOUT_MS)
})
])
} catch (e) {
this._log('error', e.message || String(e))
started = false
}
if (!started) {
this._log('error', 'PCM 采集启动失败(插件未生效或麦克风被占用)')
this._cleanup(false)
return false
}
this._setStatus('recording')
this._log('info', `PCM 已启动,边录边传 ${DEMO_RECORD_MS / 1000}s 后结束`)
this._timer = setTimeout(() => {
this.stopAndUpload()
}, DEMO_RECORD_MS)
return true
// #endif
}
_onPcmChunk(frame) {
this._frames.push({
seq: frame.seq,
base64: frame.base64,
byteLength: frame.byteLength,
timestamp: frame.timestamp
})
if (frame.seq % 8 === 0) {
this._log('info', `采集中 帧#${frame.seq} ${frame.byteLength}B,已缓存 ${this._frames.length} 帧,已发送 ${this._sentCount} 帧`)
}
const ws = this._ws
if (!ws?.isConnected) return
this._sendChain = this._sendChain
.then(() => this._sendPcmFrame(frame))
.catch((e) => {
this._log('warn', `发送帧#${frame.seq} 失败: ${e.message || e}`)
})
}
async _sendPcmFrame(frame) {
const ws = this._ws
if (!ws?.isConnected) return
if (!this._streamStarted) {
const ok = await ws.send({
command: 'audioStreamStart',
data: {
sampleRate: 16000,
channels: 1,
bitDepth: 16,
format: 'pcm',
demo: true
}
})
if (!ok) {
throw new Error('audioStreamStart 发送失败')
}
this._streamStarted = true
this._log('info', '已发送 audioStreamStart,开始上传 PCM 帧')
}
const ok = await ws.send({
command: 'audioStream',
data: {
seq: frame.seq,
chunk: frame.base64,
byteLength: frame.byteLength,
timestamp: frame.timestamp
}
})
if (!ok) {
throw new Error(`audioStream seq=${frame.seq} 发送失败`)
}
this._sentCount++
if (this._sentCount % 10 === 0) {
this._log('info', `实时上传 ${this._sentCount} 帧`)
}
}
async stopAndUpload() {
if (!this._running) return
clearTimeout(this._timer)
this._timer = null
this._setStatus('uploading')
this._log('info', '停止录音…')
const stream = AudioStreamService.getInstance()
if (this._chunkHandler) {
stream.offChunk(this._chunkHandler)
this._chunkHandler = null
}
stream.stop()
await this._sendChain.catch(() => {})
const total = this._frames.length
const bytes = this._frames.reduce((sum, f) => sum + (f.byteLength || 0), 0)
this._log('info', `录音结束:采集 ${total} 帧 / 已发送 ${this._sentCount} 帧,约 ${(bytes / 1024).toFixed(1)} KB`)
const ws = this._ws
if (ws?.isConnected && this._streamStarted) {
try {
await ws.send({
command: 'audioStreamEnd',
data: { total, sent: this._sentCount, bytes }
})
this._log('info', `已发送 audioStreamEnd sent=${this._sentCount}`)
} catch (e) {
this._log('error', `audioStreamEnd 失败: ${e.message || e}`)
}
} else if (total === 0) {
this._log('warn', '未采集到 PCM 数据,未向服务端发送音频')
} else if (!this._streamStarted) {
this._log('warn', '未发送 audioStreamStart,跳过 audioStreamEnd')
}
this._cleanup(true)
}
cancel() {
clearTimeout(this._timer)
this._timer = null
const stream = AudioStreamService.getInstance()
if (this._chunkHandler) {
stream.offChunk(this._chunkHandler)
this._chunkHandler = null
}
stream.stop()
this._cleanup(false)
this._log('warn', 'Demo 已取消')
}
async _ensureRecordPermission() {
// #ifdef APP-PLUS
if (plus.os.name === 'Android') {
const code = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO')
return code === 1
}
// #endif
return true
}
_cleanup(done) {
this._running = false
this._frames = []
this._streamStarted = false
this._sentCount = 0
this._sendChain = Promise.resolve()
if (this._ws) {
this._ws.onMessage = this._prevOnMessage
}
if (this._ownsWs && this._ws) {
this._ws.close().catch(() => {})
NativeWsClient.resetInstance()
}
this._ws = null
this._prevOnMessage = null
this._ownsWs = false
this._setStatus(done ? 'done' : 'idle')
}
_log(level, msg) {
const entry = demoLog(level, msg)
this._onLog(entry)
}
_setStatus(status) {
this._onStatus(status)
}
}
/*
* @Description: PCM 实时流服务(Android UTS 插件封装)
* 用法:
* const stream = AudioStreamService.getInstance()
* stream.onChunk((frame) => { ... })
* stream.start() / stream.stop()
*/
import { DEFAULT_FRAME_SIZE, DEFAULT_SAMPLE_RATE } from './constants.js'
import { normalizePcmFrame } from './pcmUtils.js'
// #ifdef APP-PLUS
import {
startPcmCapture,
stopPcmCapture,
onPcmFrame,
offPcmFrame
} from '@/uni_modules/gl-pcm-capture'
// #endif
class AudioStreamService {
static _instance = null
constructor() {
this._listeners = new Set()
this._running = false
this._frameHandler = null
this._logEveryN = 50
this._frameCount = 0
this._lastError = ''
}
get lastError() {
return this._lastError
}
static getInstance() {
if (!AudioStreamService._instance) {
AudioStreamService._instance = new AudioStreamService()
}
return AudioStreamService._instance
}
/**
* 订阅 PCM 帧
* @param {(frame: object) => void} callback frame 含 base64、buffer(ArrayBuffer)、seq 等
* @returns {() => void} 取消订阅
*/
onChunk(callback) {
if (typeof callback !== 'function') {
return () => {}
}
this._listeners.add(callback)
return () => this._listeners.delete(callback)
}
offChunk(callback) {
this._listeners.delete(callback)
}
get isRunning() {
return this._running
}
/**
* @param {object} [options]
* @param {number} [options.sampleRate]
* @param {number} [options.frameSize]
* @param {boolean} [options.debugLog] 是否打印采样日志
*/
start(options = {}) {
// #ifndef APP-PLUS
uni.$logger?.local?.warn('[AudioStream] 仅 App 端支持')
return Promise.resolve(false)
// #endif
// #ifdef APP-PLUS
if (plus.os.name !== 'Android') {
uni.$logger?.local?.warn('[AudioStream] 当前仅实现 Android PCM 采集')
return Promise.resolve(false)
}
if (typeof startPcmCapture !== 'function') {
this._lastError = 'gl-pcm-capture 未加载(缺少 utssdk/index.uts 或未打自定义基座)'
uni.$logger?.local?.error(`[AudioStream] ${this._lastError}`)
return Promise.resolve(false)
}
if (this._running) {
return Promise.resolve(true)
}
this._lastError = ''
const sampleRate = options.sampleRate || DEFAULT_SAMPLE_RATE
const frameSize = options.frameSize || DEFAULT_FRAME_SIZE
const debugLog = options.debugLog !== false
this._frameHandler = (frame) => {
const normalized = normalizePcmFrame(frame)
this._frameCount++
if (debugLog && this._frameCount % this._logEveryN === 1) {
uni.$logger?.local?.info(
`[AudioStream] frame#${normalized.seq} bytes=${normalized.byteLength} ts=${normalized.timestamp}`
)
}
this._listeners.forEach((cb) => {
try {
cb(normalized)
} catch (e) {
uni.$logger?.local?.error(`[AudioStream] listener error: ${e.message}`)
}
})
}
onPcmFrame(this._frameHandler)
return new Promise((resolve) => {
try {
startPcmCapture({
sampleRate,
frameSize,
success: () => {
this._running = true
this._frameCount = 0
uni.$logger?.local?.info('[AudioStream] PCM 采集已启动')
resolve(true)
},
fail: (err) => {
offPcmFrame()
this._frameHandler = null
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
}
stop() {
// #ifdef APP-PLUS
if (plus.os.name === 'Android') {
stopPcmCapture()
offPcmFrame()
}
// #endif
this._running = false
this._frameHandler = null
this._frameCount = 0
uni.$logger?.local?.info('[AudioStream] PCM 采集已停止')
}
}
export default AudioStreamService
/** 接待录音时是否同步启动 PCM 流采集(Android) */
export const ENABLE_PCM_STREAM = true
/** 默认采样率,与接待录音一致 */
export const DEFAULT_SAMPLE_RATE = 16000
/** 每帧字节数,约 128ms @ 16kHz mono 16bit */
export const DEFAULT_FRAME_SIZE = 4096
import FloatLogBus from '@/utils/logger/FloatLogBus.js'
const DEMO_TAG = '[AudioDemo]'
export function demoLog(level, msg) {
const text = `${DEMO_TAG} ${msg}`
const logger = uni.$logger?.local
// 只走 logger;若已 install FloatLogBus,logger 监听器会同步到悬浮窗,避免重复打两条
if (logger?.[level]) {
logger[level](text)
} else {
console.log(text)
try {
if (!FloatLogBus.isInstalled()) {
FloatLogBus.install()
}
FloatLogBus.push(level, text)
} catch (_) {
/* ignore */
}
}
return { level, text, time: Date.now() }
}
import AudioStreamService from './AudioStreamService.js'
import AudioStreamDemoRunner from './AudioStreamDemoRunner.js'
import { ENABLE_PCM_STREAM, DEFAULT_SAMPLE_RATE, DEFAULT_FRAME_SIZE } from './constants.js'
import { base64ToArrayBuffer, normalizePcmFrame } from './pcmUtils.js'
import { demoLog } from './demoLog.js'
export {
AudioStreamService,
AudioStreamDemoRunner,
ENABLE_PCM_STREAM,
DEFAULT_SAMPLE_RATE,
DEFAULT_FRAME_SIZE,
base64ToArrayBuffer,
normalizePcmFrame,
demoLog
}
export default AudioStreamService
/**
* base64 PCM → ArrayBuffer
* @param {string} base64
* @returns {ArrayBuffer}
*/
export function base64ToArrayBuffer(base64) {
if (typeof uni !== 'undefined' && typeof uni.base64ToArrayBuffer === 'function') {
return uni.base64ToArrayBuffer(base64)
}
const binary = atob(base64)
const len = binary.length
const bytes = new Uint8Array(len)
for (let i = 0; i < len; i++) {
bytes[i] = binary.charCodeAt(i)
}
return bytes.buffer
}
/**
* 将插件帧数据标准化,附带 ArrayBuffer
* @param {object} frame
* @returns {object}
*/
export function normalizePcmFrame(frame) {
return {
...frame,
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,7 +13,7 @@ import permission from '@/js_sdk/wa-permission/permission.js'
import store from '@/store'
import PathUtils from './PathUtils.js'
import AudioFramePool from './AudioFramePool.js'
import AiChatWsService from '@/utils/aiAssistant/AiChatWsService.js'
import NativeChannelClient, { TransportType, getNativeWsBase } from '@/utils/socket'
class RecordService {
static instance = null
......@@ -25,6 +25,8 @@ class RecordService {
this._startAudioPromise = null
this.timeoutService = null
this._initDone = false
/** AI 通道:接待开始时确定(默认 HTTP;配置了 NATIVE_WS_BASE 则走 WS) */
this._aiClient = null
// 音频帧缓冲池,保留最近 60 秒的 PCM 数据
this.framePool = new AudioFramePool({ maxSeconds: 60, sampleRate: 16000 })
// 保存初始化 Promise,startAudio 会等待
......@@ -113,7 +115,7 @@ class RecordService {
}
this.audioManager.start()
this.timeoutService.start()
AiChatWsService.getInstance().connectForReception({ fromReception: true })
await this._ensureAiClientForReception()
return true // 返回 true 表示成功启动
} catch (e) {
uni.$logger.local.error(`【录音服务RecordService】 == startAudio 异常: ${e.message}\n${e.stack}`)
......@@ -248,7 +250,7 @@ class RecordService {
}
uni.$logger.local.info('【录音服务RecordService】 == 结束接待! ')
this.stop()
AiChatWsService.getInstance().disconnectReception()
await this._teardownAiClientForReception().catch(() => {})
try {
await this.saveAndClearRecord(isNotSave)
} catch (error) {
......@@ -283,6 +285,47 @@ class RecordService {
this.timeoutService?.stop()
}
/** 获取当前接待的 AI client(可能为 null,表示未开始接待或初始化失败) */
getAiClient() {
return this._aiClient
}
async _ensureAiClientForReception() {
const wsBase = (getNativeWsBase() || '').trim()
const useWs = !!wsBase
const transport = useWs ? TransportType.WEBSOCKET : TransportType.HTTP
// HTTP 服务端固定为 /health(可在 AiAssistantBall 内按需覆盖)
const httpBaseUrl = 'http://192.168.10.141:8616'
const client = new NativeChannelClient(
useWs ? { transport } : { transport, baseUrl: httpBaseUrl }
)
this._aiClient = client
if (useWs) {
try {
uni.$logger?.local?.info(`[AI] 接待开始,使用 WS: ${wsBase}`)
await client.connectDirect(wsBase)
} catch (e) {
uni.$logger?.local?.warn(`[AI] WS 连接失败,回退 HTTP: ${e.message || e}`)
this._aiClient = new NativeChannelClient({ transport: TransportType.HTTP, baseUrl: httpBaseUrl })
}
} else {
uni.$logger?.local?.info(`[AI] 接待开始,使用 HTTP: ${httpBaseUrl}`)
}
}
async _teardownAiClientForReception() {
const client = this._aiClient
this._aiClient = null
if (!client) return
if (client.transport === TransportType.WEBSOCKET) {
await client.close(1000, 'reception end', true).catch(() => {})
} else {
await client.close().catch(() => {})
}
}
handler(params, fn, delay = 0) {
if (this.isReceptioning()) {
fn.call(this, params)
......
/*
* 统一通道客户端:构造时选择 http / websocket,对外 API 一致
*
* const client = new NativeChannelClient({ transport: 'websocket' })
* const client = new NativeChannelClient({ transport: 'http', sendPath: '/message', auth: true })
*/
import { TransportType } from './constants.js'
import NativeWsClient from './NativeWsClient.js'
import NativeHttpClient from './NativeHttpClient.js'
class NativeChannelClient {
/**
* @param {object} [options]
* @param {'http'|'websocket'} [options.transport='websocket']
* @param {string} [options.baseUrl] HTTP 根地址(http 模式)
* @param {string} [options.sendPath] HTTP send 路径(http 模式)
* @param {string} [options.wsUrl] WebSocket 地址覆盖(websocket 模式,写入 NATIVE_WS_BASE 逻辑由 ws 客户端处理)
* @param {Function} [options.onMessage]
*/
constructor(options = {}) {
const transport = options.transport || TransportType.WEBSOCKET
this.transport = transport
if (transport === TransportType.HTTP) {
this._impl = new NativeHttpClient(options)
} else {
this._impl = new NativeWsClient()
if (options.wsUrl) {
this._impl.wsAddress = options.wsUrl
}
}
if (typeof options.onMessage === 'function') {
this._impl.onMessage = options.onMessage
}
}
get isConnected() {
return this._impl.isConnected
}
get deviceId() {
return this._impl.deviceId
}
get token() {
return this._impl.token
}
get onMessage() {
return this._impl.onMessage
}
set onMessage(handler) {
this._impl.onMessage = handler
}
connect() {
return this._impl.connect()
}
connectDirect(url) {
if (this.transport !== TransportType.WEBSOCKET) {
return Promise.reject(new Error('connectDirect 仅支持 websocket 模式'))
}
return this._impl.connectDirect(url)
}
send(data, type) {
return this._impl.send(data, type)
}
sendJson(obj) {
if (typeof this._impl.sendJson === 'function') {
return this._impl.sendJson(obj)
}
return this._impl.send(obj)
}
close(...args) {
return this._impl.close(...args)
}
waitUntilConnected(timeoutMs) {
return this._impl.waitUntilConnected(timeoutMs)
}
/** 仅 http 模式:底层 uni.request */
request(options) {
if (this.transport !== TransportType.HTTP) {
return Promise.reject(new Error('request 仅支持 http 模式'))
}
return this._impl.request(options)
}
}
export default NativeChannelClient
/*
* 原生 HTTP 客户端(uni.request)
* - 默认不鉴权:request()/send() 直接可用,不需要 connect()
* - auth=true 时:connect() 会调用 /login 拿 token/deviceId,并在请求中自动附加
*/
import config from '@/config.js'
import { serializeIfObject } from '@/utils/utils.js'
import { loginDevice } from './wsAuth.js'
import { normalizeWsPayload } from './wsMessage.js'
import { DEFAULT_HTTP_OPTIONS } from './constants.js'
const DEFAULT_TYPE = 'private'
class NativeHttpClient {
/**
* @param {object} [options]
* @param {string} [options.baseUrl] HTTP 根地址,默认 config.HTTP_SERVER
* @param {string} [options.sendPath] send 请求路径,默认 /message
* @param {string} [options.method] 默认 POST
* @param {object} [options.header] 额外请求头
* @param {number} [options.timeout]
*/
constructor(options = {}) {
this.baseUrl = (options.baseUrl || config.HTTP_SERVER || '').replace(/\/+$/, '')
this.sendPath = options.sendPath || DEFAULT_HTTP_OPTIONS.sendPath
this.method = (options.method || DEFAULT_HTTP_OPTIONS.method).toUpperCase()
this.header = { 'Content-Type': 'application/json', ...(options.header || {}) }
this.timeout = options.timeout ?? DEFAULT_HTTP_OPTIONS.timeout
this.dataType = options.dataType || DEFAULT_HTTP_OPTIONS.dataType
this.auth = options.auth === true || (options.auth && options.auth.enabled === true)
this.token = ''
this.deviceId = ''
this.onMessage = null
// HTTP 无“连接”概念;仅在启用 auth 时,connect() 用于拉取 token/deviceId
this._tag = options.logTag || DEFAULT_HTTP_OPTIONS.logTag
}
get isConnected() {
// HTTP 默认认为可用;若启用鉴权,则以 token 是否存在作为“已连接/已就绪”
return this.auth ? !!this.token : true
}
async connect() {
if (!this.auth) {
return
}
const loginRes = await loginDevice()
const code = loginRes?.code
if (code != 200 && code != 0) {
throw new Error(`登录失败 code=${code}`)
}
const data = loginRes.data || {}
this.deviceId = data.id
this.token = data.token
if (!this.deviceId || !this.token) {
throw new Error('登录返回缺少 id 或 token')
}
this._log('info', `HTTP 已登录 deviceId=${this.deviceId}`)
}
/**
* 通用 uni.request 封装(相对路径自动拼 baseUrl)
* @param {object} options uni.request 参数,url 可为相对路径
*/
request(options = {}) {
const url = this._resolveUrl(options.url)
if (!url) {
return Promise.reject(new Error('request 缺少 url'))
}
const header = { ...this.header, ...(options.header || {}) }
if (this.auth && this.token && !header.token) {
header.token = this.token
}
return new Promise((resolve, reject) => {
uni.request({
timeout: this.timeout,
dataType: this.dataType,
...options,
url,
header,
success: (res) => resolve(res),
fail: (err) => reject(err)
})
})
}
send(data, type = DEFAULT_TYPE) {
if (this.auth && !this.token) {
this._log('warn', 'HTTP 需要鉴权:请先 connect() 获取 token/deviceId')
return Promise.resolve(false)
}
let body
if (typeof data === 'string') {
try {
body = JSON.parse(data)
} catch {
body = { raw: data }
}
} else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
this._log('warn', 'HTTP 模式暂不支持 ArrayBuffer,请使用 JSON')
return Promise.resolve(false)
} else {
body = {
...data,
...(this.auth && this.deviceId ? { device_id: this.deviceId } : {}),
...(data.type != null ? { type: data.type } : this.auth ? { type } : {})
}
}
const url = this._resolveUrl(this.sendPath)
return new Promise((resolve) => {
uni.request({
url,
method: this.method,
header: this.auth && this.token ? { ...this.header, token: this.token } : { ...this.header },
data: body,
timeout: this.timeout,
dataType: this.dataType,
success: (res) => {
const ok = res.statusCode >= 200 && res.statusCode < 300
if (!ok) {
this._log('warn', `send 非 2xx status=${res.statusCode} ${serializeIfObject(res.data)}`)
resolve(false)
return
}
const parsed = normalizeWsPayload(res.data)
this._log('info', `收到 <= ${JSON.stringify(parsed).slice(0, 240)}`)
this.onMessage && this.onMessage(parsed)
resolve(true)
},
fail: (err) => {
this._log('warn', `send 失败: ${serializeIfObject(err)}`)
resolve(false)
}
})
})
}
sendJson(obj) {
return this.send(obj)
}
async close() {
this.token = ''
this.deviceId = ''
this._log('info', '会话已关闭')
}
async waitUntilConnected(timeoutMs = 15000) {
if (this.isConnected) return true
const start = Date.now()
while (Date.now() - start < timeoutMs) {
if (this.isConnected) return true
await new Promise((r) => setTimeout(r, 200))
}
return false
}
_resolveUrl(path) {
if (!path) return ''
if (/^https?:\/\//i.test(path)) return path
const p = path.startsWith('/') ? path : `/${path}`
return `${this.baseUrl}${p}`
}
_log(level, msg) {
const text = `[${this._tag}] ${msg}`
const logger = uni.$logger?.local
if (logger?.[level]) {
logger[level](text)
} else if (level === 'error') {
console.error(text)
} else if (level === 'warn') {
console.warn(text)
} else {
console.log(text)
}
}
}
export default NativeHttpClient
......@@ -2,6 +2,9 @@
* 原生 WebSocket 客户端(SocketTask)
* 协议对齐 venus uniapp-x-tape/ws/Ws.uts
* API 对齐 https://uniapp.dcloud.net.cn/api/request/websocket.html
*
* - connect(): 走 /login 拿 token/deviceId,然后按 `NATIVE_WS_BASE`(若设置)或 `SOCKET_SERVER + WS_NATIVE_PATH` 连接
* - connectDirect(url): 不登录,直接连接指定 url(用于独立服务)
*/
import config from '@/config.js'
import { serializeIfObject } from '@/utils/utils.js'
......
/** 传输层类型 */
export const TransportType = {
WEBSOCKET: 'websocket',
HTTP: 'http'
}
/** WebSocket 连接状态 */
export const SocketState = {
IDLE: 'idle',
......@@ -8,18 +14,20 @@ export const SocketState = {
}
export const DEFAULT_OPTIONS = {
/** 断线后是否自动重连 */
reconnect: true,
/** 重连间隔(ms) */
reconnectInterval: 3000,
/** 最大重连次数,-1 表示不限 */
reconnectMaxRetries: -1,
/** 未连接时是否缓存 send 队列 */
enableSendQueue: true,
/** send 队列上限 */
sendQueueMax: 100,
/** 收到文本消息时尝试 JSON.parse */
autoParseJson: true,
/** 日志标签 */
logTag: 'SocketClient'
}
/** HTTP 客户端默认配置 */
export const DEFAULT_HTTP_OPTIONS = {
sendPath: '/message',
method: 'POST',
timeout: 30000,
dataType: 'json',
logTag: 'NativeHttp'
}
import SocketClient from './SocketClient.js'
import NativeWsClient from './NativeWsClient.js'
import { createSocketTask, connectSocketTask, isSocketTask } from './connectSocketTask.js'
import { SocketState, DEFAULT_OPTIONS } from './constants.js'
import NativeHttpClient from './NativeHttpClient.js'
import NativeChannelClient from './NativeChannelClient.js'
import {
SocketState,
DEFAULT_OPTIONS,
DEFAULT_HTTP_OPTIONS,
TransportType
} from './constants.js'
import {
WS_NATIVE_PATH,
NATIVE_WS_BASE,
......@@ -15,13 +20,13 @@ import { normalizeWsPayload } from './wsMessage.js'
import { loginDevice } from './wsAuth.js'
export {
SocketClient,
NativeWsClient,
createSocketTask,
connectSocketTask,
isSocketTask,
NativeHttpClient,
NativeChannelClient,
TransportType,
SocketState,
DEFAULT_OPTIONS,
DEFAULT_HTTP_OPTIONS,
WS_NATIVE_PATH,
NATIVE_WS_BASE,
setNativeWsBase,
......@@ -32,4 +37,6 @@ export {
normalizeWsPayload,
loginDevice
}
export default SocketClient
/** 统一通道客户端(推荐业务使用) */
export default NativeChannelClient
......@@ -4,6 +4,7 @@
*
* 使用方:
* - utils/socket/NativeWsClient(原生 SocketTask / 音频 Demo)
* - utils/socket/NativeHttpClient(仅在 auth=true 时)
* 不使用方:
* - ws/Ws.js 主业务 socket.io(自带 login(),未引用本文件)
*/
......
......@@ -5,8 +5,6 @@
* WebSocket 与 HTTP 共用同一套服务,地址由服务端提供后填到 NATIVE_WS_BASE。
* 不修改 config.js / env.js。
*/
import config from '@/config.js'
/** SOCKET_SERVER 仅为域名时自动拼接的路径 */
export const WS_NATIVE_PATH = '/ws-native'
......@@ -14,7 +12,7 @@ export const WS_NATIVE_PATH = '/ws-native'
* 原生 WS 完整 base(不含 ?token=),服务端提供后填写,例如:
* ws://host:8081/ws-native
*/
export let NATIVE_WS_BASE = 'wss://echo.websocket.org'
export let NATIVE_WS_BASE = ''
export function setNativeWsBase(url) {
NATIVE_WS_BASE = (url || '').trim()
......@@ -43,9 +41,6 @@ export function normalizeWsUrl(url) {
return trimmed
}
/** 音频对话 WebSocket(无鉴权直连) */
export const AUDIO_CHAT_WS_URL = normalizeWsUrl('http://192.168.1.203:8000/ws/audio/chat')
/**
* 从登录 data 中取服务端下发的 ws 地址(若有)
* @param {object} data
......
......@@ -38,19 +38,21 @@ const STAGE = {
MEDIA: '归并·媒体'
}
function previewList(arr, limit = 4) {
if (!Array.isArray(arr)) return { count: 0, preview: [] }
if (arr.length <= limit) return { count: arr.length, preview: arr.slice() }
return { count: arr.length, preview: arr.slice(0, limit), more: arr.length - limit }
}
function isAndroidApp(plusRef) {
const osName = plusRef?.os?.name
return !!plusRef && (osName === 'Android' || osName === 'android')
}
async function safeRemoveDocRelative(relativePath, label) {
logStep(STAGE.DB, `清理临时文件:${relativePath}`, { 说明: label })
const ok = await removeDocRelative(relativePath)
if (ok) {
logStep(STAGE.DB, `临时文件已删除:${relativePath}`)
} else {
logStep(STAGE.DB, `临时文件不存在或无需删除:${relativePath}`)
}
// 仅在真正删除成功时记录,避免刷屏(不存在属于常态)
if (ok) logStep(STAGE.DB, `临时文件已删除:${relativePath}`, label ? { 说明: label } : undefined)
return ok
}
......@@ -68,17 +70,12 @@ async function mergeFromDbFile(dbPath, label, mergePkg) {
}
const hint = isOwnAppStoragePath(dbPath, mergePkg) ? '本应用' : '其它'
logStep(STAGE.DB, '开始处理来源库', { 来源: dbPath, 标签: tag, 归属: hint })
logStep(STAGE.DB, '处理来源库', { 来源: dbPath, 标签: tag, 归属: hint })
await safeRemoveDocRelative(TEMP_DB_FILE, '合并前清理旧临时库')
logStep(STAGE.DB, '开始复制来源库到 _doc 临时库', {
来源: dbPath,
目标: `_doc/${TEMP_DB_FILE}`
})
try {
await copyFileToDoc(dbPath, TEMP_DB_FILE)
logStep(STAGE.DB, '来源库复制到临时库成功', { 来源: dbPath })
} catch (e) {
logStepFail(STAGE.DB, '复制来源库到临时库失败', {
来源: dbPath,
......@@ -88,36 +85,29 @@ async function mergeFromDbFile(dbPath, label, mergePkg) {
}
try {
logStep(STAGE.DB, '打开临时库', { 路径: TEMP_DB_FILE })
await openTempDb()
logStep(STAGE.DB, '临时库打开成功')
logStep(STAGE.DB, '查询临时库 records 表')
const rows = await selectTempRecords()
const count = rows?.length || 0
logStep(STAGE.DB, '临时库 records 查询完成', { 条数: count })
logStep(STAGE.DB, '临时库 records 读取完成', { 条数: count, 来源: dbPath })
if (!rows || count === 0) {
logStep(STAGE.DB, '临时库无数据,结束本来源合并', { 标签: tag, 来源: dbPath })
await closeTempDb()
await safeRemoveDocRelative(TEMP_DB_FILE, '无数据清理临时库')
return 'empty'
}
logStep(STAGE.DB, '开始向主库合并记录', { 待合并条数: count, 来源: dbPath })
const ok = await mergeRecordsToMain(rows, { 来源: dbPath })
logStep(STAGE.DB, '关闭临时库')
await closeTempDb()
await safeRemoveDocRelative(TEMP_DB_FILE, '合并后清理临时库')
if (ok) {
logStep(STAGE.DB, '记录已写入主库,准备删除来源库', { 来源: dbPath })
logStep(STAGE.DB, '记录已写入主库', { 来源: dbPath, 条数: count })
try {
const removed = await removeFile(dbPath)
if (removed) {
logStep(STAGE.DB, '来源库删除成功', { 路径: dbPath })
logStep(STAGE.DB, '来源库已删除', { 路径: dbPath })
} else {
logStepFail(STAGE.DB, '来源库删除失败:文件未找到或无法解析', { 路径: dbPath })
}
......@@ -129,7 +119,7 @@ async function mergeFromDbFile(dbPath, label, mergePkg) {
}
return 'merged'
}
logStepFail(STAGE.DB, '写入主库未完全成功,保留来源库', { 来源: dbPath, 标签: tag })
logStepFail(STAGE.DB, '写入主库未完全成功,保留来源库', { 来源: dbPath, 条数: count, 标签: tag })
return 'merge_failed'
} catch (e) {
logStepFail(STAGE.DB, '处理来源库异常', {
......@@ -167,24 +157,17 @@ async function processPath(packageRoot, mergePkg, currentRoot, index, total) {
let outcome = 'no_db'
if (dbPath) {
if (!isRestrictedInternalPath(dbPath, mergePkg)) {
logStep(STAGE.PATH, '发现来源库', { 包根: packageRoot, 库: dbPath })
outcome = await mergeFromDbFile(dbPath, packageRoot, mergePkg)
} else {
logStepFail(STAGE.PATH, '发现库但路径受限,跳过合并', { 库路径: dbPath })
outcome = 'restricted'
}
} else {
logStep(STAGE.PATH, '该包根下未找到 zyzs.db', { 包根: packageRoot })
}
const canMarkHandled = ['no_db', 'empty', 'merged', 'restricted'].includes(outcome)
if (canMarkHandled) {
markAlternateRootHandled(currentRoot, packageRoot)
logStep(STAGE.PATH, '已记录 alternate 包根为已处理', {
包根: packageRoot,
结果: outcome
})
} else {
logStep(STAGE.PATH, '未标记已处理(便于下次重试)', { 包根: packageRoot, 结果: outcome })
}
logStep(STAGE.PATH, `包根扫描结束 (${index}/${total})`, { 包根: packageRoot, 结果: outcome })
......@@ -193,8 +176,6 @@ async function processPath(packageRoot, mergePkg, currentRoot, index, total) {
/** 主库在 apps/xxx/doc 时,包根下扁平 zyzs.db 视为遗留库 */
async function processLegacyFlatDbAtCurrentRoot(currentRoot, mergePkg) {
logStep(STAGE.PATH, '开始检查当前包根遗留扁平库')
if (!currentRoot || isRestrictedInternalPath(currentRoot, mergePkg)) {
logStep(STAGE.PATH, '跳过遗留扁平库检查', {
原因: !currentRoot ? '无当前包根' : '内部路径受限',
......@@ -207,21 +188,16 @@ async function processLegacyFlatDbAtCurrentRoot(currentRoot, mergePkg) {
const flatDb = `${root}/${DB_FILE}`
const mainDocDb = normalizePath(`${root}/apps/${getAppId()}/doc/${DB_FILE}`)
logStep(STAGE.PATH, '探测遗留扁平库路径', { 扁平库: flatDb, 主库doc: mainDocDb })
if (!(await fileExists(flatDb))) {
logStep(STAGE.PATH, '当前包根无遗留扁平库', { 路径: flatDb })
return
}
if (normalizePath(flatDb) === mainDocDb) {
logStep(STAGE.PATH, '扁平库与主 doc 库为同一路径,跳过', { 路径: flatDb })
return
}
logStep(STAGE.PATH, '发现遗留扁平库,进入合并流程', { 路径: flatDb })
await mergeFromDbFile(flatDb, `${currentRoot}#legacy-flat`, mergePkg)
logStep(STAGE.PATH, '遗留扁平库检查结束')
}
class StoragePathMerge {
......@@ -262,10 +238,7 @@ class StoragePathMerge {
}
static async executeRun({ force = false } = {}) {
logStep(STAGE.RUN, '======== 路径合并开始 ========')
logStep(STAGE.RUN, '目标:外置 emulated ↔ 内部 /data/data、/data/user')
logStep(STAGE.RUN, '等待 Plus 环境就绪')
logStep(STAGE.RUN, '======== 路径合并开始 ========', { force })
const plusRef = await waitForPlus()
if (!isAndroidApp(plusRef)) {
logStep(STAGE.RUN, '结束:非 Android APP-PLUS,跳过归并', {
......@@ -274,14 +247,11 @@ class StoragePathMerge {
})
return
}
logStep(STAGE.RUN, 'Plus 环境就绪', { 系统: plusRef?.os?.name })
logStep(STAGE.RUN, '运行环境确认:Android APP-PLUS', { 系统: plusRef?.os?.name })
try {
logStep(STAGE.RUN, '初始化主库 uni.$dbRecord.init()')
await uni.$dbRecord.init()
logStep(STAGE.RUN, '主库 init 完成')
logStep(STAGE.RUN, '解析当前包根与 doc 路径')
const currentRoot = await getCurrentPackageRoot()
const currentDocPath = normalizePath(await PathUtils.getFilePath())
const mergePkg = getRuntimePackageName()
......@@ -293,19 +263,14 @@ class StoragePathMerge {
appId: getAppId()
})
logStep(STAGE.RUN, '加载 PathCache')
let cache = loadPathCache()
if (!cache || !cache.length) {
logStep(STAGE.RUN, 'PathCache 为空,创建默认缓存')
cache = createDefaultCache(currentRoot)
} else {
logStep(STAGE.RUN, 'PathCache 已存在,补全默认包根', { 条目数: cache.length })
cache = ensureDefaultRootsInCache(cache, currentRoot)
}
savePathCache(cache)
logStep(STAGE.RUN, 'PathCache 已保存', {
条目: cache.map(c => ({ 路径: c.path, 当前: c.isCurrent }))
})
logStep(STAGE.RUN, 'PathCache 就绪', { 条目数: cache?.length || 0 })
const nonCurrentItems = getNonCurrentPaths(cache)
const allAlternateRoots = nonCurrentItems.map(p => p.path)
......@@ -315,17 +280,20 @@ class StoragePathMerge {
}
const scanPlan = planAlternateScan(currentRoot, nonCurrentItems, force)
const altPreview = previewList(allAlternateRoots, 4)
logStep(STAGE.RUN, 'alternate 包根扫描计划', {
说明: '均为当前 app 在不同沙箱下的包根(外置 /data/data /data/user),非其它应用',
全部非当前包根: allAlternateRoots,
计划: scanPlan
非当前包根数: altPreview.count,
预览: altPreview.preview,
...(altPreview.more ? { 其余: altPreview.more } : {}),
跳过: !!scanPlan.skip,
...(scanPlan.skip ? { 原因: scanPlan.reason } : { 扫描数: scanPlan.paths?.length || 0 })
})
const appId = getAppId()
const alternateSaveDirs = allAlternateRoots.map(root => resolveUniappSaveDir(root, appId))
if (scanPlan.skip) {
logStep(STAGE.RUN, '跳过 alternate 库扫描', { 原因: scanPlan.reason })
// 已在扫描计划里输出原因
} else {
const scanList = scanPlan.paths
const total = scanList.length
......
......@@ -10,7 +10,6 @@ const tempSqlite = new SQLite(TEMP_DB_NAME, '1.0', 'path merge temp', 50 * 1024
export async function openTempDb() {
try {
await tempSqlite.init()
logStep(STAGE, 'SQLite 临时库 init 成功', { 逻辑名: TEMP_DB_NAME, 路径: TEMP_DB_PATH })
return true
} catch (e) {
logStepFail(STAGE, 'SQLite 临时库 init 失败', { 错误: e?.message || String(e) })
......@@ -22,9 +21,6 @@ export async function closeTempDb() {
try {
if (tempSqlite.isOpen()) {
await tempSqlite.closeDatabase()
logStep(STAGE, 'SQLite 临时库已关闭', { 逻辑名: TEMP_DB_NAME })
} else {
logStep(STAGE, 'SQLite 临时库本就未打开,无需关闭')
}
} catch (e) {
logStepFail(STAGE, 'SQLite 临时库关闭失败', { 错误: e?.message || String(e) })
......@@ -32,15 +28,11 @@ export async function closeTempDb() {
}
export async function selectTempRecords() {
logStep(STAGE, `检查临时库是否存在表 ${TABLE_NAME}`)
const exists = await tempSqlite.isTableExists(TABLE_NAME)
if (!exists) {
logStep(STAGE, `临时库无 ${TABLE_NAME} 表,视为 0 条`)
return []
}
logStep(STAGE, `执行 SELECT * FROM ${TABLE_NAME}`)
const rows = await tempSqlite.selectSql(`SELECT * FROM ${TABLE_NAME}`)
logStep(STAGE, '临时库查询完成', { 条数: rows?.length || 0 })
return rows
}
......@@ -55,7 +47,6 @@ function getDbRecord() {
/** 依赖 uni.$dbRecord.init() 已建表,直接向主库插入 */
export async function mergeRecordsToMain(rows, meta = {}) {
const total = rows?.length || 0
logStep(STAGE, '逐条合并到主库', { 待处理: total, ...meta })
const dbRecord = getDbRecord()
let merged = 0
......@@ -65,14 +56,12 @@ export async function mergeRecordsToMain(rows, meta = {}) {
for (const record of rows) {
if (!record || !record.id) {
skipped++
logStepFail(STAGE, '跳过无效记录(无 id)', { 记录: record })
continue
}
try {
const exists = await dbRecord.getRecordById(record.id)
if (exists) {
skipped++
logStep(STAGE, `主库已存在,跳过 id=${record.id}`)
continue
}
await dbRecord.addRecord(record)
......
......@@ -81,13 +81,9 @@ export async function copyFileToDoc(sourceAbsolutePath, destFileName) {
const destRel = destFileName.startsWith('_doc/') ? destFileName : `_doc/${destFileName}`
const destAbs = resolvePlusAbsolutePath(destRel)
logStep(STAGE, '开始复制到 _doc', { 来源: src, 目标相对: destRel, 目标绝对: destAbs })
if (isInternalSandboxAbsPath(src)) {
logStep(STAGE, '内部沙箱路径,使用 Java File API', { 来源: src })
try {
const out = await copyFileByAndroid(src, destAbs)
logStep(STAGE, 'File API 复制成功', { 目标: out })
return out
} catch (e) {
logStepFail(STAGE, 'File API 复制失败', { 来源: src, 错误: e?.message || String(e) })
......@@ -95,18 +91,14 @@ export async function copyFileToDoc(sourceAbsolutePath, destFileName) {
}
}
logStep(STAGE, '外置/可访问路径,尝试 plus.io 复制')
try {
const out = await copyFileToDocByPlusIo(src, destFileName)
logStep(STAGE, 'plus.io 复制成功', { 结果: out })
return out
} catch (e) {
const msg = e?.message || String(e)
if (isInternalSandboxAbsPath(src) || /36199|不支持当前路径|targetSdk/i.test(msg)) {
logStep(STAGE, 'plus.io 失败,降级 File API', { 原因: msg })
try {
const out = await copyFileByAndroid(src, destAbs)
logStep(STAGE, '降级 File API 复制成功', { 目标: out })
return out
} catch (e2) {
logStepFail(STAGE, '降级 File API 仍失败', { 错误: e2?.message || String(e2) })
......@@ -181,16 +173,9 @@ export async function copyFileIntoDocSaveDir(sourceAbsolutePath, destFileName) {
const src = String(sourceAbsolutePath).trim()
const destAbs = resolvePlusAbsolutePath(`_doc/${UNIAPP_SAVE_DIR}/${destFileName}`)
logStep(STAGE, '开始复制录音到 uniapp_save', {
来源: src,
文件名: destFileName,
目标: destAbs
})
if (isInternalSandboxAbsPath(src)) {
try {
const out = await copyFileByAndroid(src, destAbs)
logStep(STAGE, '录音 File API 复制成功', { 目标: out })
return out
} catch (e) {
logStepFail(STAGE, '录音 File API 复制失败', { 错误: e?.message || String(e) })
......@@ -200,15 +185,12 @@ export async function copyFileIntoDocSaveDir(sourceAbsolutePath, destFileName) {
try {
const out = await copyIntoDocSaveDirByPlusIo(src, destFileName)
logStep(STAGE, '录音 plus.io 复制成功', { 结果: out })
return out
} catch (e) {
const msg = e?.message || String(e)
if (/36199|不支持当前路径|targetSdk/i.test(msg)) {
logStep(STAGE, '录音 plus.io 失败,降级 File API', { 原因: msg })
try {
const out = await copyFileByAndroid(src, destAbs)
logStep(STAGE, '录音降级复制成功', { 目标: out })
return out
} catch (e2) {
logStepFail(STAGE, '录音降级复制失败', { 错误: e2?.message || String(e2) })
......
......@@ -45,7 +45,8 @@ export function derivePackageRootFromDocPath(docPath) {
export async function getCurrentPackageRoot() {
const docPath = await PathUtils.getFilePath()
const root = derivePackageRootFromDocPath(docPath)
logStep(STAGE, '由 doc 路径推导包根', { doc: normalizePath(docPath), 包根: root })
// 冷启动期间该信息较稳定,避免重复刷屏,仅保留关键结果
logStep(STAGE, '推导包根完成', { 包根: root })
return root
}
......@@ -63,18 +64,13 @@ export function resolveDbFilePaths(packageRoot) {
export async function findDbInPackageRoot(packageRoot) {
const candidates = resolveDbFilePaths(packageRoot)
logStep(STAGE, '开始探测数据库候选路径', { 包根: packageRoot, 候选数: candidates.length })
for (let i = 0; i < candidates.length; i++) {
const path = candidates[i]
const exists = await fileExists(path)
logStep(STAGE, `候选 (${i + 1}/${candidates.length})`, { 路径: path, 存在: exists })
if (exists) {
logStep(STAGE, '命中数据库文件', { 路径: path, 包根: packageRoot })
logStep(STAGE, '命中数据库文件', { 路径: path })
return path
}
}
logStep(STAGE, '未命中任何候选库', { 包根: packageRoot })
return null
}
......@@ -57,11 +57,8 @@ export async function verifyAndRepairRecordMediaPaths(currentDocPath, alternateS
const altDirs = (alternateSaveDirs || []).map(d => normalizePath(d)).filter(Boolean)
const curDoc = normalizePath(currentDocPath)
logStep(STAGE, '读取主库 records 用于媒体校验', {
doc根: curDoc,
备用录音目录数: altDirs.length,
备用目录: altDirs
})
// 冷启动时该流程可能处理大量记录/片段,避免逐条打印,仅保留汇总与关键修复/失败
logStep(STAGE, '媒体路径校验准备', { doc根: curDoc, 备用录音目录数: altDirs.length })
try {
const rows = await dbRecord.db.selectSql(`SELECT id, recordUrlList, tempFilePath FROM ${TABLE_NAME}`)
......@@ -69,7 +66,6 @@ export async function verifyAndRepairRecordMediaPaths(currentDocPath, alternateS
logStep(STAGE, '主库 records 读取完成', { 记录数: rowCount })
if (rowCount === 0) {
logStep(STAGE, '无记录需校验媒体,结束')
return { okCount: 0, missingCount: 0, repairedCount: 0 }
}
......@@ -81,7 +77,6 @@ export async function verifyAndRepairRecordMediaPaths(currentDocPath, alternateS
for (const row of rows || []) {
idx++
if (!row?.id) {
logStepFail(STAGE, `记录 (${idx}/${rowCount}) 无 id,跳过`)
continue
}
......@@ -92,12 +87,6 @@ export async function verifyAndRepairRecordMediaPaths(currentDocPath, alternateS
let recordMissing = 0
let recordRepaired = 0
logStep(STAGE, `校验记录 (${idx}/${rowCount})`, {
recordId: row.id,
片段数: list.length,
有tempFilePath: !!tempFilePath
})
for (const item of list) {
if (!item?.file) continue
const path = item.file
......@@ -117,19 +106,10 @@ export async function verifyAndRepairRecordMediaPaths(currentDocPath, alternateS
continue
}
logStep(STAGE, `片段不可读,尝试从备用目录修复 recordId=${row.id}`, {
表内路径: path,
文件名: fileName
})
let repaired = false
for (const altDir of altDirs) {
const candidate = `${altDir}/${fileName}`
const altExists = await fileExists(candidate)
logStep(STAGE, `检查备用副本 recordId=${row.id}`, {
候选: candidate,
存在: altExists
})
if (!altExists) continue
try {
......@@ -139,10 +119,7 @@ export async function verifyAndRepairRecordMediaPaths(currentDocPath, alternateS
repaired = true
repairedCount++
recordRepaired++
logStep(STAGE, `片段修复成功 recordId=${row.id}`, {
来源: candidate,
新路径: item.file
})
logStep(STAGE, `片段修复成功 recordId=${row.id}`, { 文件名: fileName })
break
} catch (e) {
logStepFail(STAGE, `片段从备用目录复制失败 recordId=${row.id}`, {
......@@ -169,10 +146,6 @@ export async function verifyAndRepairRecordMediaPaths(currentDocPath, alternateS
missingCount++
recordMissing++
const fileName = extractFileNameFromMediaPath(tempFilePath)
logStep(STAGE, `tempFilePath 不可读 recordId=${row.id}`, {
路径: tempFilePath,
文件名: fileName
})
let tempRepaired = false
for (const altDir of altDirs) {
......@@ -185,7 +158,7 @@ export async function verifyAndRepairRecordMediaPaths(currentDocPath, alternateS
repairedCount++
recordRepaired++
tempRepaired = true
logStep(STAGE, `tempFilePath 修复成功 recordId=${row.id}`, { 新路径: tempFilePath })
logStep(STAGE, `tempFilePath 修复成功 recordId=${row.id}`, { 文件名: fileName })
break
} catch (e) {
logStepFail(STAGE, `tempFilePath 复制失败 recordId=${row.id}`, {
......@@ -201,7 +174,6 @@ export async function verifyAndRepairRecordMediaPaths(currentDocPath, alternateS
}
if (listChanged) {
logStep(STAGE, `回写主库路径 recordId=${row.id}`)
try {
await dbRecord.updateRecord(
{
......@@ -210,21 +182,12 @@ export async function verifyAndRepairRecordMediaPaths(currentDocPath, alternateS
},
{ id: row.id }
)
logStep(STAGE, `主库路径已更新 recordId=${row.id}`)
} catch (e) {
logStepFail(STAGE, `主库路径更新失败 recordId=${row.id}`, {
错误: e?.message || String(e)
})
}
}
logStep(STAGE, `记录 (${idx}/${rowCount}) 校验小结`, {
recordId: row.id,
可读片段: recordOk,
不可读: recordMissing,
已修复: recordRepaired,
是否更新表: listChanged
})
}
logStep(STAGE, '媒体校验汇总', {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!