一次录制一个音频,然后停止以保存在ReactJS中

时间:2018-12-04 10:17:26

标签: javascript reactjs getusermedia

当麦克风关闭时,我正在使用getUserMedia() API来录制音频。点击时,我正在调用 startRecord 方法

{this.props.events.map((event) => (
 <div  key={event.event_name}>
    <div> {this.state.micStates[event.event_name]?
     <span onClick={()=>this.stopRecord(event.event_name)}> <MicOn /> 
     </span> 
     :<span onClick={()=>this.startRecord(event.event_name)}><MicOff />       
    </span>}              
   </div>
   <li style={{color:'pink',}}>{event.date_time}</li>
 </div> ))
}

两种方法: startRecord StopRecord

startRecord :它将开始录制并分块存储

stopRecord :它将停止 mediaRecorder 并将文件保存在 formData

 constructor(props) {
            super(props);            
            this.state = {
              mediaRecorder : [],
              audioURL : [],
              micStates: {},
            }
       this.startRecord = this.startRecord.bind(this);
       this.stopRecord = this.stopRecord.bind(this);
    }

   startRecord = event => {
         this.setState(current => ({
           micStates: { ...current.micStates, [event]: 
             !current.micStates[event] }
         }));
        let constraints = { audio: true }

      navigator.mediaDevices.getUserMedia(constraints)
        .then(function(stream) {
            audioContext = new AudioContext();
            gumStream = stream;
            input = audioContext.createMediaStreamSource(stream);
            this.mediaRecorder = new MediaRecorder(input,{numChannels:1})

            this.chunks = [];
             // listen for data from media recorder
               rec.ondataavailable = e => {
                  if (e.data && e.data.size > 0) {
                   this.chunks.push(e.data);
               }
          };
            this.mediaRecorder.start(10);
            console.log("Recording started");
        }).catch(function(err) {
              //enable the record button if getUserMedia() fails
        });
    }

    stopRecord = event => {
        this.setState(current => ({
            micStates: { ...current.micStates, [event]: 
            !current.micStates[event] }
        }));
         this.mediaRecorder.stop();
         var blob = new Blob(this.state.chunks, {type: 'audio/*'});
         this.setState({ audioURL: window.URL.createObjectURL(blob)})
    }

第一个问题: TypeError:无法读取未定义的属性“ stop” 在这一行this.mediaRecorder.stop();

第二个问题:我可以打开多个音频,这意味着无需调用stopRecord方法就可以调用另一个事件的startRecord方法

0 个答案:

没有答案