【问题标题】:How to record audio and video using JAVASCRIPT ? (REACT JS)如何使用 JAVASCRIPT 录制音频和视频? (反应 JS)
【发布时间】:2021-12-10 07:00:42
【问题描述】:

我试过了,但是有错误“TypeError: Cannot read properties of undefined (reading 'stop')” 我在按钮单击时调用函数 这里也是函数:)

const getAudio= async ()=>{

         let device = await navigator.mediaDevices.getUserMedia({audio: true});
         let chunks = [];
         let recorder;
         device.then(stream => {
             recorder = new MediaRecorder(stream);
             recorder.ondataavailable = e => {
                 chunks.push(e.data);
                 if (recorder.state === 'inactive') {
                     this.blob = new Blob(chunks, {type: 'audio/webm'});
                     let testAudioRecord  = URL.createObjectURL(this.blob);
                     console.log(testAudioRecord)
                 }
             }
             recorder.start(1000);
         });
         setTimeout(() => {
             recorder.stop();     //   Cannot read ('stop') =error
         }, 2000)
     }

【问题讨论】:

    标签: javascript reactjs audio video web-mediarecorder


    【解决方案1】:

    我发现在使用 async with await 和 .then 承诺处理之间存在一些混淆。

    由于您使用的是异步函数,因此让我们重构为 try...catch 并使用 await 等待承诺解决。

      const getAudio = async () => {
        let chunks = [];
        let recorder;
    
        try {
          //wait for the stream promise to resolve
          let stream = await navigator.mediaDevices.getUserMedia({ audio: true });
          recorder = new MediaRecorder(stream);
          recorder.ondataavailable = (e) => {
            chunks.push(e.data);
            if (recorder.state === "inactive") {
              this.blob = new Blob(chunks, { type: "audio/webm" });
              let testAudioRecord = URL.createObjectURL(this.blob);
              console.log(testAudioRecord);
            }
          };
          recorder.start(1000);
    
          setTimeout(() => {
            recorder.stop();
          }, 2000);
        } catch (e) {
          console.log("error getting stream", e);
        }
      };
    

    有更好的方法来构建代码,但这应该可以让你的函数正常工作。

    这是一个codesandbox,其中包含您的功能和播放选项

    这是另一个音频codesandbox

    【讨论】:

      猜你喜欢
      • 2021-04-12
      • 1970-01-01
      • 2014-08-02
      • 2012-05-08
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多