Skip to content

录音 useRecord 文档

更新: 2025/1/20 字数: 0 字 时长: 0 分钟

基础使用

useRecord 用于录制音频以及提供语音转文字的功能。

开始录音

startRecord 用于开始录音。

ts
import useRecord from "@/hooks/useRecord";
const { startRecord } = useRecord();
点击查看示例代码
vue
<script setup lang="ts">
const status = ref(0); // 0-未开始or录制完毕 1-录音中 2-暂停
function startRecordFn() {
  startRecord();
  status.value = 1;
}
</script>
<template>
  <van-button v-if="status === 0" class="btn" @click="startRecordFn">
    <template #icon>
      <van-icon name="play-circle-o" />
    </template>
    开始录音
  </van-button>
</template>

暂停录音

pauseRecord 用于暂停录音。

ts
import useRecord from "@/hooks/useRecord";
const { pauseRecord } = useRecord();
点击查看示例代码
vue
<script setup lang="ts">
const status = ref(0); // 0-未开始or录制完毕 1-录音中 2-暂停
function pauseRecordFn() {
  pauseRecord();
  status.value = 2;
}
</script>
<template>
  <van-button class="btn" @click="pauseRecordFn">
    <template #icon>
      <van-icon name="pause-circle-o" />
    </template>
    暂停录音
  </van-button>
</template>

恢复录音

resumeRecord 用于恢复录音,需要在暂停录音后使用。

ts
import useRecord from "@/hooks/useRecord";
const { resumeRecord } = useRecord();
点击查看示例代码
vue
<script setup lang="ts">
const status = ref(0); // 0-未开始or录制完毕 1-录音中 2-暂停
function resumeRecordFn() {
  resumeRecord();
  status.value = 1;
}
</script>
<template>
  <van-button v-if="status === 2" class="btn" @click="resumeRecordFn">
    <template #icon>
      <van-icon name="play-circle-o" />
    </template>
    继续录音
  </van-button>
</template>

结束录音

stopRecord 用于结束录音,返回一个audio/acc类型的base64编码字符串,存在audioUrl里。

ts
import useRecord from "@/hooks/useRecord";
const { stopRecord } = useRecord();
点击查看示例代码
vue
<script setup lang="ts">
const status = ref(0); // 0-未开始or录制完毕 1-录音中 2-暂停
function stopRecordFn() {
  stopRecord();
  status.value = 0;
}
watch(
  () => audioUrl.value,
  (val) => {
    if (val) {
      nextTick(() => {
        const audioBlob = base64ToBlob(val);
        const url = URL.createObjectURL(audioBlob);
        audioPlayer.value.src = url;
      });
    }
  },
);
</script>
<template>
  <div>
    <van-button class="mr-10 btn" @click="stopRecordFn">
      <template #icon>
        <van-icon name="stop-circle-o" />
      </template>
      结束录音
    </van-button>
    <audio v-if="audioUrl" ref="audioPlayer" controls></audio>
  </div>
</template>

API

返回值、方法

返回值、方法说明类型
audioUrl录音结束后的audio/acc类型的base64编码字符串string
startRecord开始录音() => Promise
pauseRecord暂停录音() => Promise
resumeRecord恢复录音() => Promise
stopRecord结束录音() => Promise

Released under the MIT License.

本站访客数 人次 本站总访问量