Record audio one at a time and stop to save in ReactJS

喜欢而已 提交于 2020-01-06 05:51:12

问题


I am using getUserMedia() API to record audio when mic is off I am calling startRecord method on it's click

{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> ))
}

Two methods: startRecord, StopRecord

startRecord: It will start the recording and store in chunks

stopRecord: It will stop the mediaRecorder and save the file in 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)})
    }

First Problem: TypeError: Cannot read property 'stop' of undefined at this line this.mediaRecorder.stop();

Second Problem: I can switch on multiple audio means that without calling method stopRecord I can call startRecord method of another event

来源:https://stackoverflow.com/questions/53610608/record-audio-one-at-a-time-and-stop-to-save-in-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!