Записывайте аудио по одному и останавливайтесь, чтобы сохранить в ReactJS - PullRequest
0 голосов
/ 04 декабря 2018

Я использую 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' undefined в этой строке this.mediaRecorder.stop();

Вторая проблема: Я могу включить несколько аудио, значит, что без вызова метода stopRecord я могу вызватьметод startRecord другого события

...