是否可以在不使用麦克风的情况下录制<audio>的输出?

max*_*ner 2 html javascript audio html5-audio webrtc

我有一个<audio>元素,并且要更改速度,开始/结束范围和音高。我想看看是否可以在浏览器中录制我听到的音频。但是由于质量较低,我不想只用麦克风录音。

我可以在服务器端执行相同的效果,但我宁愿不这样做,因为我基本上会使用两种不同的技术来复制相同的功能。


由于“我不清楚我要问的是什么”,因此对国旗表决作出回应,我将重新表述。

<audio>在页面上播放一个元素。我有一些Javascript操作播放率,音量等。然后,我希望浏览器听到声音时记录下来。这不是麦克风。我想创建一个新的音频文件,该文件与正在播放的音频文件尽可能接近。如果为75%,则新文件的音量为75%。

Kai*_*ido 6

在支持的浏览器中,您可以将MediaElement.captureStream()方法与MediaRecorder API一起使用。

但是请注意,这些技术仍在积极开发中,并且当前的实现仍然充满错误。
例如,就您的情况而言,如果您在录制时更改音量,当前稳定的FF将停止呈现原始媒体音频。您会发现许多错误。

// here we will save all the chunks of our record
const chunks = [];
// wait for the original media is ready
audio.oncanplay = function() {
  audio.volume = 0.5; // just for your example
  // FF still does prefix this unstable method
  var stream = audio.captureStream ? audio.captureStream() : audio.mozCaptureStream();
  // create a MediaRecorder from our stream
  var rec = new MediaRecorder(stream);
  // every time we've got a bit of data, store it
  rec.ondataavailable = e => chunks.push(e.data);
  // once everything is done
  rec.onstop = e => {
    audio.pause();
    // concatenate our chunks into one file
    let final = new Blob(chunks);
    let a = new Audio(URL.createObjectURL(final));
    a.controls = true;
    document.body.append(a);
  };
  rec.start();
  // record for 6 seconds
  setTimeout(() => rec.stop(), 6000);
  // for demo, change volume at half-time
  setTimeout(() => audio.volume = 1, 3000);
};

// FF will "taint" the stream, even if the media is served with correct CORS...
fetch("https://dl.dropboxusercontent.com/s/8c9m92u1euqnkaz/GershwinWhiteman-RhapsodyInBluePart1.mp3").then(resp => resp.blob()).then(b => audio.src = URL.createObjectURL(b));
Run Code Online (Sandbox Code Playgroud)
<audio id="audio" autoplay controls></audio>
Run Code Online (Sandbox Code Playgroud)

对于较旧的浏览器,您可以使用WebAudio API的createMediaElementSource方法通过API传递音频元素媒体。
从那里,您可以将原始PCM数据提取到arrayBuffers并保存。

在下面的演示中,我将使用recorder.js库,它对于提取+保存到wav过程有很大帮助。

audio.oncanplay = function(){
  var audioCtx = new AudioContext();
  var source = audioCtx.createMediaElementSource(audio);
  var gainNode = audioCtx.createGain();

  gainNode.gain.value = 0.5;

  source.connect(gainNode);
  gainNode.connect(audioCtx.destination);  

  var rec = new Recorder(gainNode);

   rec.record();
  setTimeout(function(){
    gainNode.gain.value = 1;
    }, 3000);
  setTimeout(function(){
    rec.stop()
    audio.pause();
    rec.exportWAV(function(blob){
      var a = new Audio(URL.createObjectURL(blob));
      a.controls = true;
      document.body.appendChild(a);
      });
    }, 6000);
  };
Run Code Online (Sandbox Code Playgroud)
<script src="https://rawgit.com/mattdiamond/Recorderjs/master/dist/recorder.js"></script>
<audio id="audio" crossOrigin="anonymous" controls src="https://dl.dropboxusercontent.com/s/8c9m92u1euqnkaz/GershwinWhiteman-RhapsodyInBluePart1.mp3" autoplay></audio>
Run Code Online (Sandbox Code Playgroud)