pcmUtils.js 1.23 KB
/**
 * 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
}