Commit 3096a148 by liimin

refactor(recordManager): 优化原生录音器并发控制与异步清理

- 将 `clearSavedFiles` 和 `setReceptionEndTime` 改为异步方法,确保文件删除顺序
- 重构策略工厂以延迟选择具体策略类,简化实例化逻辑
- 优化原生录音器状态管理:移除冗余状态,添加准备阶段并发检查点
- 缓存 Java 类引用和目录路径,避免重复导入与检查
- 统一使用 `uni.$logger` 替换 `console` 进行日志记录
- 添加 `release` 方法供页面销毁时显式释放资源
1 parent c72aa873
...@@ -12,9 +12,7 @@ import PathUtils from './PathUtils.js' ...@@ -12,9 +12,7 @@ import PathUtils from './PathUtils.js'
// 录音状态枚举 // 录音状态枚举
const RecorderState = { const RecorderState = {
IDLE: 'idle', // 空闲 IDLE: 'idle', // 空闲
RECORDING: 'recording', // 录音中 RECORDING: 'recording' // 录音中
PAUSED: 'paused', // 暂停 (暂未实现,预留)
ERROR: 'error' // 错误状态
} }
// 默认配置 // 默认配置
...@@ -43,6 +41,10 @@ class NativeRecorder { ...@@ -43,6 +41,10 @@ class NativeRecorder {
error: [] error: []
} }
// 缓存 Java 类
this._JavaFile = null
this._JavaMediaRecorder = null
// 绑定上下文,防止调用时 this 丢失 // 绑定上下文,防止调用时 this 丢失
this.start = this.start.bind(this) this.start = this.start.bind(this)
this.stop = this.stop.bind(this) this.stop = this.stop.bind(this)
...@@ -88,7 +90,7 @@ class NativeRecorder { ...@@ -88,7 +90,7 @@ class NativeRecorder {
try { try {
cb(data) cb(data)
} catch (e) { } catch (e) {
console.error(`[NativeRecorder] Event handler error (${event}):`, e) uni.$logger.local.error(`[NativeRecorder] Event handler error (${event}):`, e)
} }
}) })
}, 0) }, 0)
...@@ -110,12 +112,31 @@ class NativeRecorder { ...@@ -110,12 +112,31 @@ class NativeRecorder {
} }
/** /**
* 确保保存目录存在 * 延迟加载 Java 类
*/
_loadJavaClasses() {
// #ifdef APP-PLUS
if (!this._JavaFile) {
this._JavaFile = plus.android.importClass('java.io.File')
}
if (!this._JavaMediaRecorder) {
this._JavaMediaRecorder = plus.android.importClass('android.media.MediaRecorder')
}
// #endif
}
/**
* 确保保存目录存在 (带缓存)
* @param {string} dirPath - 相对路径,如 _doc/uniapp_save/ * @param {string} dirPath - 相对路径,如 _doc/uniapp_save/
* @returns {Promise<string>} - 绝对路径 (Java File 使用) * @returns {Promise<string>} - 绝对路径 (Java File 使用)
*/ */
_ensureSaveDir(dirPath) { async _ensureSaveDir(dirPath) {
return PathUtils.ensureDir(dirPath) if (this._cachedDir?.path === dirPath && this._cachedDir.absPath) {
return this._cachedDir.absPath
}
const absPath = await PathUtils.ensureDir(dirPath)
this._cachedDir = { path: dirPath, absPath: absPath }
return absPath
} }
/** /**
...@@ -128,25 +149,38 @@ class NativeRecorder { ...@@ -128,25 +149,38 @@ class NativeRecorder {
return return
} }
// 防止重复启动 // 如果正在录音,先停止
if (this._state === RecorderState.RECORDING) { if (this._state === RecorderState.RECORDING) {
console.warn('[NativeRecorder] Already recording, stopping first...') uni.$logger.local.warn('[NativeRecorder] Already recording, stopping first...')
await this.stop() await this.stop()
} }
// 设置为准备状态,加锁
// 注意:虽然没有显式的 PREPARING 状态,但 RECORDING 状态配合下面的检查点逻辑
// 已经实现了"准备中"的并发控制
this._state = RecorderState.RECORDING
try { try {
// #ifdef APP-PLUS // #ifdef APP-PLUS
// 1. 导入必要的 Android 类 // 1. 导入必要的 Android 类
const MediaRecorder = plus.android.importClass('android.media.MediaRecorder') this._loadJavaClasses()
const File = plus.android.importClass('java.io.File') const MediaRecorder = this._JavaMediaRecorder
const File = this._JavaFile
// 2. 准备路径 // 2. 准备路径
// 使用 TempRecord 统一管理的路径逻辑,避免多处硬编码 // 使用 TempRecord 统一管理的路径逻辑,避免多处硬编码
// 这里的 options.path 如果未提供,使用 DEFAULT_CONFIG.basePath // 这里的 options.path 如果未提供,使用 DEFAULT_CONFIG.basePath
const basePath = options.path || DEFAULT_CONFIG.basePath const basePath = options.path || DEFAULT_CONFIG.basePath
// _ensureSaveDir 负责将相对路径转换为绝对路径 // _ensureSaveDir 负责将相对路径转换为绝对路径
// 【关键点】这里是异步操作,期间可能会被 stop() 中断
const saveDirAbsPath = await this._ensureSaveDir(basePath) const saveDirAbsPath = await this._ensureSaveDir(basePath)
// 【检查点】如果异步期间状态变回 '' (IDLE)(说明被 stop 打断),则终止
if (this._state !== RecorderState.RECORDING) {
uni.$logger.local.warn('[NativeRecorder] Start cancelled during preparation')
return
}
// 使用 UUID + 时间戳 确保文件名唯一性,防止多用户并发上传到 OSS 时文件名冲突 // 使用 UUID + 时间戳 确保文件名唯一性,防止多用户并发上传到 OSS 时文件名冲突
// 格式: {uuid}_{timestamp}.mp3 // 格式: {uuid}_{timestamp}.mp3
const uuidStr = utils.uuid(8, 16) // 生成8位长度的UUID,基数为16 const uuidStr = utils.uuid(8, 16) // 生成8位长度的UUID,基数为16
...@@ -186,7 +220,9 @@ class NativeRecorder { ...@@ -186,7 +220,9 @@ class NativeRecorder {
} }
// 6. 更新状态 // 6. 更新状态
this._state = RecorderState.RECORDING // 此时状态应该已经是 RECORDING,无需再次设置,但为了保险确认一下
if (this._state !== RecorderState.RECORDING) return
uni.$logger.local.info(`[NativeRecorder] Started: ${this._currentFilePath}`) uni.$logger.local.info(`[NativeRecorder] Started: ${this._currentFilePath}`)
const fileUrl = 'file://' + this._currentFilePath const fileUrl = 'file://' + this._currentFilePath
this._emit('start', { this._emit('start', {
...@@ -207,8 +243,16 @@ class NativeRecorder { ...@@ -207,8 +243,16 @@ class NativeRecorder {
stop() { stop() {
if (!this._checkEnvironment()) return if (!this._checkEnvironment()) return
if (this._state !== RecorderState.RECORDING || !this._mediaRecorder) { if (this._state !== RecorderState.RECORDING) {
console.warn('[NativeRecorder] Not recording or recorder not initialized') // 已经是空闲,无需操作
return
}
// 无论 MediaRecorder 是否初始化,stop 的意图都是结束录音
// 如果 _mediaRecorder 为空,说明还在准备阶段,直接清理即可
if (!this._mediaRecorder) {
uni.$logger.local.warn('[NativeRecorder] Stopping while preparing (no mediaRecorder instance)')
this._cleanup()
return return
} }
...@@ -223,13 +267,14 @@ class NativeRecorder { ...@@ -223,13 +267,14 @@ class NativeRecorder {
} catch (stopErr) { } catch (stopErr) {
// 常见错误:RuntimeException: stop failed. // 常见错误:RuntimeException: stop failed.
// 原因:录音时间太短(通常小于 1 秒)或尚未开始 // 原因:录音时间太短(通常小于 1 秒)或尚未开始
console.warn('[NativeRecorder] Stop exception (likely too short):', stopErr) uni.$logger.local.warn('[NativeRecorder] Stop exception (likely too short):', stopErr)
// 这种情况下,文件可能无效或未生成,需要检查文件是否存在 // 这种情况下,文件可能无效或未生成,需要检查文件是否存在
} }
uni.$logger.local.info(`[NativeRecorder] Stopped`) uni.$logger.local.info(`[NativeRecorder] Stopped`)
// 检查文件是否存在且大小 > 0 // 检查文件是否存在且大小 > 0
const File = plus.android.importClass('java.io.File') this._loadJavaClasses()
const File = this._JavaFile
const file = new File(this._currentFilePath) const file = new File(this._currentFilePath)
if (file.exists() && file.length() > 0) { if (file.exists() && file.length() > 0) {
// 转换为 uni-app 可用的 file:// 路径 // 转换为 uni-app 可用的 file:// 路径
...@@ -238,7 +283,7 @@ class NativeRecorder { ...@@ -238,7 +283,7 @@ class NativeRecorder {
filePath: fileUrl filePath: fileUrl
}) })
} else { } else {
console.warn('[NativeRecorder] Recorded file invalid (empty or missing)') uni.$logger.local.warn('[NativeRecorder] Recorded file invalid (empty or missing)')
// 可以选择是否抛出 error,或者静默失败 // 可以选择是否抛出 error,或者静默失败
// this._emit('error', { errMsg: 'Recorded file invalid' }) // this._emit('error', { errMsg: 'Recorded file invalid' })
} }
...@@ -254,8 +299,8 @@ class NativeRecorder { ...@@ -254,8 +299,8 @@ class NativeRecorder {
* 内部错误处理 * 内部错误处理
*/ */
_handleError(context, error) { _handleError(context, error) {
console.error(`[NativeRecorder] ${context}:`, error) uni.$logger.local.error(`[NativeRecorder] ${context}:`+ error.message)
this._state = RecorderState.ERROR // 清理资源,直接重置为 IDLE
this._cleanup() this._cleanup()
this._emit('error', { errMsg: `${context}: ${error.message}` }) this._emit('error', { errMsg: `${context}: ${error.message}` })
} }
...@@ -284,6 +329,21 @@ class NativeRecorder { ...@@ -284,6 +329,21 @@ class NativeRecorder {
getState() { getState() {
return this._state return this._state
} }
/**
* 是否正在录音
*/
isRecording() {
return this._state === RecorderState.RECORDING
}
/**
* 显式释放资源 (供页面销毁时调用)
*/
release() {
this.stop()
this._cleanup()
}
} }
// 导出单例 // 导出单例
......
...@@ -212,12 +212,11 @@ class RecordService { ...@@ -212,12 +212,11 @@ class RecordService {
async saveAndClearRecord(isNotSave = false) { async saveAndClearRecord(isNotSave = false) {
if (isNotSave) { if (isNotSave) {
uni.$logger.local.warn('〖RecordService〗 == 不保存记录! ') uni.$logger.local.warn('〖RecordService〗 == 不保存记录! ')
this.recorder.clearSavedFiles() await this.recorder.clearSavedFiles()
this.recorder.clearLocalRecord() await this.recorder.clearLocalRecord()
return return
} }
this.recorder.setReceptionEndTime() // 设置接待结束时间 await this.recorder.setReceptionEndTime() // 设置接待结束时间
// 如果不需要保存记录 // 如果不需要保存记录
await this.recorder.save() await this.recorder.save()
} }
......
...@@ -251,11 +251,11 @@ class TempRecord { ...@@ -251,11 +251,11 @@ class TempRecord {
* @param {Object} options - 配置参数 * @param {Object} options - 配置参数
* @param {Array} options.urlList - 录音文件列表,默认为当前记录的recordUrlList * @param {Array} options.urlList - 录音文件列表,默认为当前记录的recordUrlList
*/ */
clearSavedFiles({ urlList = [] } = this.record) { async clearSavedFiles({ urlList = [] } = this.record) {
urlList.forEach(item => { for (const item of urlList) {
uni.$logger.local.info('〖接待记录Record〗 == 清除已保存文件 -> ' + item.file) uni.$logger.local.info('〖接待记录Record〗 == 清除已保存文件 -> ' + item.file)
this.removeFile(item.file) await this.removeFile(item.file)
}) }
} }
/** /**
......
...@@ -75,15 +75,14 @@ class StrategyFactory { ...@@ -75,15 +75,14 @@ class StrategyFactory {
* @param {Object} context 上下文 (通常是 TempRecord 实例需要的参数) * @param {Object} context 上下文 (通常是 TempRecord 实例需要的参数)
* @returns {Object} 保存策略实例 * @returns {Object} 保存策略实例
*/ */
static getSaveStrategy(record, onTempRecordNumberChanged, attributesProvider) { static getSaveStrategy(...args) {
let StrategyClass = PollingSave
// #ifdef APP-PLUS // #ifdef APP-PLUS
if (USE_NATIVE_RECORDER && plus.os.name === 'Android') { if (USE_NATIVE_RECORDER && plus.os.name === 'Android') {
// 实例化 NativeSaveStrategy,并传入上下文 StrategyClass = NativeSave
return new NativeSave(record, onTempRecordNumberChanged, attributesProvider)
} }
// #endif // #endif
// 实例化 PollingSaveStrategy,并传入上下文 return new StrategyClass(...args)
return new PollingSave(record, onTempRecordNumberChanged, attributesProvider)
} }
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!