js實現網頁端錄音功能

web喵神發表於2024-09-20

1、程式碼

首先安裝依賴包:recorderx

npm install recorderx -S
<template>
  <div class="container">
    <div class="mt-30">
      <el-button @click="onStartRecord">開始錄音</el-button>
      <el-button @click="onStopRecord">停止錄音</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "home",
};
</script>
<script setup>
import { reactive, ref, computed, watch, toRaw, onMounted } from "vue";
import moment from "moment";
import Recorder, { ENCODE_TYPE } from "recorderx";

let recorder;

const recordName = ref("");
function onStartRecord() {
  console.log("開始錄音");
  recorder = new Recorder(true);
  recorder
    .start()
    .then(() => {
      console.log("start recording");
    })
    .catch((error) => {
      console.log("Recording failed.", error);
    });
}

function onStopRecord() {
  console.log("停止錄音");
  recorder.pause();
  let wav = recorder.getRecord({ encodeTo: ENCODE_TYPE.WAV });
  console.log("wav", wav);

  const aLink = document.createElement("a");
  const blob = wav; // new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  aLink.style.display = "none";
  aLink.href = URL.createObjectURL(blob);
  recordName.value = moment().format("YYYYMMDDHHmmss") + ".mp3";
  aLink.setAttribute("download", recordName.value); // 設定下載檔名稱
  document.body.appendChild(aLink);
  aLink.click();
  URL.revokeObjectURL(aLink.href); // 清除引用
  document.body.removeChild(aLink);
}
</script>

2、效果

停止錄音後,檔案會自動儲存到磁碟

相關文章