HarmonyOS 鸿蒙Next:怎么可以拿到录音的时长

HarmonyOS 鸿蒙Next中参照下面这个开发,怎么可以拿到录音的时长?

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/using-audiocapturer-for-recording-V5

3 回复
公式:采样率 x (位宽 / 8) x 声道数 x 时间 = 数据大小(单位:字节)
例子:比如 2分钟的CD(采样率为:44100,位宽:16,声道数:2)的数据大小:44100 x (16 / 8) x 2 x 120 = 20671.875 Byte 约为 20.18M。
答案:secTime = dataLength / (mSampleRate * mNumChannel * mBitsPerSample / 8)

更多关于HarmonyOS 鸿蒙Next:怎么可以拿到录音的时长的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next系统中,获取录音时长通常可以通过音频文件的元数据实现。你可以使用系统提供的API或库来读取音频文件的属性,包括时长。如果系统API直接支持获取时长,则直接调用即可。如果不支持,你可能需要解析音频文件的头部信息或使用第三方库来解析音频数据,从而计算出时长。具体实现方式取决于你的应用框架和所使用的开发环境。如果问题依旧没法解决,请加我微信,我的微信是itying888。

更多关于HarmonyOS 鸿蒙Next:怎么可以拿到录音的时长的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


先把录音保存为音频文件,然后用以下方法读取音频时长 这个方法不能一边录音一边读取时长,在录音结束后再读取时长。

async getAudioDuration() {
  let avMetadataExtractor: media.AVMetadataExtractor | null = null
  try {
    if (canIUse("SystemCapability.Multimedia.Media.AVMetadataExtractor")) {
      // 创建AVMetadataExtractor对象
      let avMetadataExtractor = await media.createAVMetadataExtractor();

      if (this.filePath === null) {
        throw new GetAudioDurationError("The recording duration cannot be determined: The audio file path does not exist")
      }
      // 设置fdSrc
      const context: Context = getContext(this);
      const path: string = context.filesDir + '/audio.m4a'; // 文件沙箱路径
      avMetadataExtractor.fdSrc = fs.openSync(path);

      // 获取元数据(promise模式)
      let metadata = await avMetadataExtractor.fetchMetadata();
      const durationString = metadata.duration // 拿到的是毫秒数字符串
      if (durationString === undefined) {
        throw new GetAudioDurationError("The duration of the recording cannot be determined: The metadata of the audio file does not include the duration")
      }
      console.debug("音频时长:", durationString)
      const duration = convertMillisecondsStringToNumber(durationString)
      const seconds = duration / 1000
      return seconds
    } else {
      throw new GetAudioDurationError("The recording duration cannot be determined: The system capacity is limited")
    }
  } catch (error) {
    if (error instanceof ParseMetaDataDurationError) {
      const typedError: ParseMetaDataDurationError = error
      throw new GetAudioDurationError("The recording duration cannot be determined: " + typedError.message)
    } else {
      throw new GetAudioDurationError("The recording duration cannot be determined.\n" +
      JSON.stringify(error, null, 2))
    }
  } finally {
    // 释放资源(promise模式)
    if (avMetadataExtractor !== null) {
      const avMetadataExtractorA: media.AVMetadataExtractor = avMetadataExtractor
      avMetadataExtractorA.release()
    }
  }
}

@ObservedV2
class GetAudioDurationError extends Error {
  @Trace
  message: string

  constructor(message: string) {
    super(message)
    this.message = message
  }
}

@ObservedV2
class ParseMetaDataDurationError extends Error {
  @Trace
  message: string

  constructor(message: string) {
    super(message)
    this.message = message
  }
}

/**
 * Converts a milliseconds string to a number
 * @param {string} msString - The string representation of milliseconds
 * @returns {number} - The converted milliseconds as a number
 * @throws {Error} - If the input is not a valid milliseconds value
 */
const convertMillisecondsStringToNumber = (msString: string) => {
  // Check if input is a string
  if (typeof msString !== 'string') {
    throw new ParseMetaDataDurationError('Input must be a string');
  }

  // Trim whitespace
  const trimmedStr = msString.trim();

  // Check if string is empty
  if (trimmedStr === '') {
    throw new ParseMetaDataDurationError('Input cannot be empty');
  }

  // Check if the string contains only digits
  if (!/^\d+$/.test(trimmedStr)) {
    throw new ParseMetaDataDurationError('Input must contain only digits');
  }

  // Convert to number
  const milliseconds = Number(trimmedStr);

  // Check if the conversion resulted in a valid number
  if (!Number.isFinite(milliseconds)) {
    throw new ParseMetaDataDurationError('Failed to convert to a valid number');
  }

  // Check if the number is too large (exceeds safe integer)
  if (milliseconds > Number.MAX_SAFE_INTEGER) {
    throw new ParseMetaDataDurationError('Milliseconds value exceeds maximum safe integer');
  }

  return milliseconds;
}
回到顶部