+
22
-

回答

在Web浏览器中,直接使用MediaRecorder录制来自window.speechSynthesis(文本转语音)的音频流并不是一件直接的事情,因为MediaRecorder通常用于录制来自麦克风、摄像头或屏幕的媒体流,而window.speechSynthesis并不提供音频流接口。

但是可以通过屏幕录制getDisplayMedia实现,录制的时候选择整个屏幕,勾选同时分享系统音频。

800_auto

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum=1.0,minimum=1.0,user-scalable=0" />
    <title>BFW NEW PAGE</title>
   
     <style>
      </style>
</head>
<body>
   <button id="start">开始录制</button>
<button id="stop" disabled>停止并下载</button>
<script>
  const startBtn = document.getElementById('start');
  const stopBtn = document.getElementById('stop');
  let mediaRecorder, audioChunks = [];

  startBtn.onclick = async () => {
    // 请求屏幕+音频捕获权限
    const stream = await navigator.mediaDevices.getDisplayMedia({ 
    
      audio: true 
    });
    
    // 播放语音
    const utterance = new SpeechSynthesisUtterance('正在录制我的声音');
    window.speechSynthesis.speak(utterance);

    // 开始录制
    mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.ondataavailable = e => audioChunks.push(e.data);
    mediaRecorder.start();

    startBtn.disabled = true;
    stopBtn.disabled = false;
  };

  stopBtn.onclick = () => {
    mediaRecorder.stop();
      startBtn.disabled = true;
    stopBtn.disabled = false;
    mediaRecorder.onstop = () => {
      const blob = new Blob(audioChunks, { type: 'audio/webm' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'captured-speech.webm';
      a.click();
      audioChunks = [];
    };
  };
</script>
</body>
</html>
		

网友回复

我知道答案,我要回答