首页 > 解决方案 > 使用 Javascript 仅录制系统音频或麦克风音频

问题描述

有没有办法只用 Javascript 录制系统音频?我似乎找不到任何东西,所以欢迎任何指针。

我知道 UserMedia 和 Recorder.js,但它同时记录系统音频和麦克风音频,并且可以分开吗?有什么配置吗?

对于任何想看看的人:

$(function () {
  const upworkRecorder = {
    rec: {
      context: null,
      stream: null,
      recorder: null,
    },
    init: function () {
      if (this.rec.context === null) {
        this.rec.context = new (AudioContext || webkitAudioContext)();
        console.log(this.rec.context);
      }
    },
    start: function () {
      var onlyAudio = {
        audio: {
          sampleRate: 52000,
          channelCount: {
            ideal: 2,
            min: 1,
          },
          noiseSuppression: true,
          autoGainControl: true,
          echoCancellation: true,
          volume: 1.0,
        },
        video: false,
      };
      navigator.mediaDevices
        .getUserMedia(onlyAudio)
        .then(s => {
          console.log(s);
          this.rec.stream = s;
          this.rec.recorder = new Recorder(
            this.rec.context.createMediaStreamSource(s),
            { numChannels: 2 }
          );
          this.rec.recorder.record();
        })
        .catch(err => {
          console.log(err.message);
        });
    },
    stop: function () {
      if (this.rec.stream !== null) {
        this.rec.stream.getAudioTracks()[0].stop();
      }
      if (this.rec.recorder !== null) {
        this.rec.recorder.stop();
      }
      this.rec.recorder.exportWAV(blob => {
        let url = (window.URL || window.webkitURL).createObjectURL(blob);
        console.log(blob, url);
        const audio = document.createElement("div");
        audio.innerHTML = `<h1>Your recording</h1><audio controls src=${url}></audio>`;
        document.body.append(audio);
      });
    },
  };

  $("#start-rec").on("click", e => {
    upworkRecorder.init();
    upworkRecorder.start();
  });
  $("#pause-rec").on("click", e => {
    upworkRecorder.stop();
  });
});

标签: javascriptaudio

解决方案


推荐阅读