interruptRecord.js 8.01 KB
/*
 * @Author: 前端 qianduan01@didihu.com.cn
 * @Date: 2024-10-14 17:38:35
 * @LastEditors: 前端 qianduan01@didihu.com.cn
 * @LastEditTime: 2024-11-20 17:27:29
 * @FilePath: \gl-tape\utils\recordManager\interruptRecord.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import RecordManager from '../RecordManager.js'
import utils from '@/utils/utils.js'
import { storageApi } from '../cache'
import store from '@/store'
let Interval = null
class InterruptRecord extends RecordManager {
  constructor() {
    super()
    const records = this.getRecords()
    store.dispatch('audio/setPerRecordNumber', records.length)
    // console.log(store)
    // storageApi.removeRecords('preRecordList')
    // storageApi.removeRecords('preRecordId')
    // storageApi.removeRecords('recordList')
  }
  records = {}
  pathName = null
  audioPath = null
  /**
   * 获取记录列表
   *
   * @returns {Array} - 从 storageApi 获取的记录列表
   */
  getRecords() {
    console.log(storageApi.getRecords('preRecordList'), 'ddd')
    return storageApi.getRecords('preRecordList') || []
  }
  /**
   * 获取待提交的记录id
   *
   */
  getPreRecord() {
    const id = storageApi.getRecords('preRecordId')
    if (!id) {
      return
    }
    return this.getRecordById(id)
  }
  /**
   * 删除待提交的记录
   *
   */
  removePreRecord(id) {
    uni.$logger.local.info(`删除待提交的记录${id}`)
    this.removeRecord(id)
    storageApi.setRecords('', 'preRecordId')
    clearInterval(Interval)
  }
  /**
   * 初始化保存记录
   *
   * @param {string} name - 录音文件目录名
   * @returns {void} - 此函数不返回任何值
   */
  async addPreRecords(params) {
    if (storageApi.getRecords('preRecordId')) {
      uni.$logger.local.info(`添加录音${storageApi.getRecords('preRecordId')}`)
      this.addPreAudio()
      return
    }
    const pathName = await this.getAudioPathName()
    const audioPath = await this.getAudioPath(pathName)
    this.audioPath = audioPath
    const id = utils.uuid()
    storageApi.setRecords(id, 'preRecordId')
    const ids = storageApi.getRecords('preRecordId')
    console.log(ids, 'id')
    this.records = {
      id,
      ...params,
      audioPath: [audioPath]
    }
    uni.$logger.local.info(`开始保存记录${id}`)
    const records = this.getRecords() || []
    records.push(this.records)
    this.setRecords(records)
    this.setLoopAudio()
    storageApi.setRecords('', 'preAudioList')
  }
  /**
   * 30s保存录音文件
   *
   */
  setLoopAudio() {
    Interval = setInterval(() => {
      this.updateAudio()
    }, 1000 * 30)
  }
  async updateAudio() {
    const len = this.records.audioPath.length - 1
    const saveResult = await uni.saveFile({
      tempFilePath: this.audioPath
    })
    const preAudioList = storageApi.getRecords('preAudioList') || []
    const filePath = preAudioList[len]
    const savedFilePath = saveResult[1].savedFilePath
    if (filePath) {
      uni.removeSavedFile({
        filePath: filePath,
        complete: () => {
          console.log('complete')
        }
      })
    }
    preAudioList[len] = savedFilePath
    console.log(preAudioList, 'preAudioList')
    storageApi.setRecords(preAudioList, 'preAudioList')
  }
  get getPreAudioList() {
    return storageApi.getRecords('preAudioList')
  }

  /**
   * 添加录音文件
   *
   * @returns {void} - 此函数不返回任何值
   */
  async addPreAudio() {
    clearInterval(Interval)
    this.updateAudio()
    const pathName = await this.getAudioPathName()
    const audioPath = await this.getAudioPath(pathName)
    this.audioPath = audioPath
    const addAudioPath = [...this.records.audioPath, audioPath]
    this.records.audioPath.push(audioPath)
    const records = this.getPreRecord()
    const params = { ...records, audioPath: addAudioPath }
    this.updateRecord(params)
    this.setLoopAudio()
  }
  /**
   * 更新参数
   *
   * @returns {void} - 此函数不返回任何值
   */
  updatePreRecords(params, isRemoveId) {
    if (isRemoveId) {
      uni.$logger.local.info(`清除正在接待记录的id`)
      storageApi.setRecords('', 'preRecordId')
      clearInterval(Interval)
    }
    const updateParams = { ...this.records, ...params }
    console.log(updateParams, 'updateParams')
    this.updateRecord(updateParams)
  }
  /**
   * 获取录音文件全路径
   *
   * @param {string} name - 录音文件目录名
   * @returns {void} - 此函数不返回任何值
   */
  async getAudioPath(name) {
    console.log(name, 'name')
    return new Promise(async (resolve, reject) => {
      const path = await utils.getAudioFilePath(name + '/recorder')
      console.log(path, 'path')
      plus.io.resolveLocalFileSystemURL(
        path,
        e => {
          var dirR = e.createReader()
          dirR.readEntries(
            function (er) {
              Promise.all(
                er.map((item, index) => {
                  return new Promise(resolve => {
                    item.getMetadata(metadata => {
                      resolve({
                        index: index,
                        name: item.name,
                        modificationTime: new Date(metadata.modificationTime).getTime()
                      })
                    })
                  })
                })
              ).then(results => {
                console.log(results, 'results')
                // 找到修改时间最晚的文件
                const latest = results.reduce(
                  (acc, current) => {
                    if (current.modificationTime > acc.modificationTime) {
                      return current
                    }
                    return acc
                  },
                  { modificationTime: 0 }
                )

                // 修改时间最晚的文件名
                resolve(path + '/' + latest.name)
              })
            },
            err => {
              reject(err)
            }
          )
        },
        err => {}
      )
    })
  }
  /**
   * 获取录音文件名
   *
   * @returns {void} - 此函数不返回任何值
   */
  async getAudioPathName() {
    return new Promise(async (resolve, reject) => {
      const path = await utils.getAudioFilePath()
      plus.io.resolveLocalFileSystemURL(
        path,
        e => {
          var dirR = e.createReader()
          dirR.readEntries(
            function (er) {
              Promise.all(
                er.map((item, index) => {
                  console.log(item, 'item')
                  return new Promise(resolve => {
                    item.getMetadata(metadata => {
                      resolve({
                        index: index,
                        name: item.name,
                        modificationTime: new Date(metadata.modificationTime).getTime()
                      })
                    })
                  })
                })
              ).then(results => {
                console.log(results, 'results')
                results = results.filter(i => i.name.startsWith('uniapp_temp'))
                // 找到修改时间最晚的文件
                const latest = results.reduce(
                  (acc, current) => {
                    if (current.modificationTime > acc.modificationTime) {
                      return current
                    }
                    return acc
                  },
                  { modificationTime: 0 }
                )

                // 修改时间最晚的文件名
                resolve(latest.name)
              })
            },
            err => {
              reject(err)
            }
          )
        },
        err => {}
      )
    })
  }
  /**
   * 设置记录列表
   *
   * @param {Array} records - 要设置的记录列表
   * @returns {void} - 此函数不返回任何值
   */
  setRecords(records) {
    storageApi.setRecords(records, 'preRecordList')
    console.log(records, 'records')
    store.dispatch('audio/setPerRecordNumber', records.length)
  }
}
export default new InterruptRecord()