使用chrome.tabCapture.capture()和MediaRecorder()时,tab的原始音频被静音

时间:2020-06-11 09:59:51

标签: javascript web-audio-api

当我将chrome.tabCapture.capture()与MediaRecorder API一起使用来记录我正在捕获的选项卡的流原始音频被静音,但录制的流中音频正常时,我希望选项卡中的音频正常运行.. ..

class Recorder {
  constructor(onChunksAvailable) {
    this.chunks = [];

    this.active = false;

    this.callback = onChunksAvailable;
  }

  start(stream) {
    if (this.active) {
      throw new Error("recorder is already running");
    }
    this.recorder = new MediaRecorder(stream, {
      mimeType: "audio/webm",
    });

    this.recorder.onstop = () => {
      stream.getAudioTracks()[0].stop();
      this.callback([...this.chunks]);

      setTimeout(() => {
        this.chunks = [];
      });

      this.active = false;
    };

    this.recorder.ondataavailable = (event) => this.chunks.push(event.data);

    this.active = true;
    this.recorder.start();
  }

  stop() {
    if (!this.active) {
      throw new Error("recorder is already stop");
    } else {
      this.recorder.stop();
    }
  }
}

let rec = new Recorder(async (chunks) => {
//using chunks then to get the stream
});

chrome.tabCapture.capture(
    {
      audio: true,
      video: false,
    },
    function (stream) {
        rec.start(stream);
}

1 个答案:

答案 0 :(得分:0)

原谅我几年前上次使用这些API时缺少文档的知识,但是MDN有一些东西。

在我的情况下,将这3行添加到start函数中是固定的。

this.context = new AudioContext();
this.stream = this.context.createMediaStreamSource(stream);
this.stream.connect(this.context.destination);
class Recorder {
  constructor(onChunksAvailable) {
    this.chunks = [];

    this.active = false;

    this.callback = onChunksAvailable;

    this.context = new AudioContext();
  }

  start(stream) {
    if (this.active) {
      throw new Error("recorder is already running");
    }

    // Reconnect the stream to actual output
    this.stream = this.context.createMediaStreamSource(stream);
    this.stream.connect(this.context.destination);

    this.recorder = new MediaRecorder(stream, {
      mimeType: "audio/webm",
    });

    this.recorder.onstop = () => {
      stream.getAudioTracks()[0].stop();
      this.callback([...this.chunks]);

      setTimeout(() => {
        this.chunks = [];
      });

      this.active = false;
    };

    this.recorder.ondataavailable = (event) => this.chunks.push(event.data);

    this.active = true;
    this.recorder.start();
  }

  stop() {
    if (!this.active) {
      throw new Error("recorder is already stop");
    } else {
      this.recorder.stop();
    }
  }
}

let rec = new Recorder(async (chunks) => {
//using chunks then to get the stream
});

chrome.tabCapture.capture(
    {
      audio: true,
      video: false,
    },
    function (stream) {
        rec.start(stream);
    })

很抱歉,由于缺少细节,但是我相信当您开始音频捕获时,它会断开流与默认输出(扬声器)的连接。通过创建辅助MediaStreamSource并将其连接到默认输出(AudioContext.destination),您可以允许流在输入到录音机的同时继续输出到扬声器。


来源

MDN: AudioContext

MDN: MediaStreamSource

Chrome extension I made 2 years ago