使用Reader.onloadend时出现问题:读取先前的数据

时间:2018-11-28 09:50:19

标签: angular recordrtc

我正在尝试理解另一个人开发的代码。简要地说,我需要记录来自麦克风的音频流,并将其发送到Google API语音识别系统。

我们正在使用recordrtc。

我有一个按钮,如果按下该按钮,则录制音频,然后再次按下,则停止录制。

问题在于停止记录功能。使用reader.onloadend,当我尝试读取音频时,总是会读取前一个音频而不是新音频,就像我处于循环中,并且读取插入第i个i-1数据一样。

这是stopRecording的代码:

stopRecording() {
    if (this.isRecording) {
      this.audioRecordingService.stopRecording();
      this.isRecording = false;
    }

    var reader = new FileReader();
    reader.readAsDataURL(this.ccc.blob); 
    reader.onloadend = function() {
        console.log("onloadend")
            var base64data = reader.result;
            localStorage.setItem("audioData", base64data.toString());                   
    }
    var data = localStorage.getItem("audioData");
    var clean_data =  data.substr(data.indexOf(',')+1);
    var post_obj = JSON.stringify({
        "name":"audio",
        "base64": clean_data
    })
    this.commandList.postBlob(post_obj).subscribe((res) => {
       console.log("Google API translation: "+ res["res"]);
    });
 }

很抱歉,如果缺少某些东西。

谢谢


为了清楚起见,我还在音频录制服务中添加了功能。希望对您有所帮助。我还检查了一下,可以确认他使用了recordRTC

 getRecordedBlob(): Observable<RecordedAudioOutput> {
   return this._recorded.asObservable();
 }

 getRecordedTime(): Observable<string> {
   return this._recordingTime.asObservable();
 }

 recordingFailed(): Observable<string> {
   return this._recordingFailed.asObservable();
 }

 startRecording() {
   if (this.recorder) {
     return;
   }

   this._recordingTime.next('00:00');
   navigator.mediaDevices.getUserMedia({ audio: true }).then(s => {
   this.stream = s;
   this.record();
 }).catch(error => {
  this._recordingFailed.next();
 });
}

abortRecording() {
  this.stopMedia();
}

private record() {
  this.recorder = new RecordRTC.StereoAudioRecorder(this.stream, {
  type: 'audio',
  numberOfAudioChannels: 1, // or leftChannel:true
  mimeType: 'audio/webm'
});

this.recorder.record();
this.startTime = moment();
this.interval = setInterval(
  () => {
    const currentTime = moment();
    const diffTime = moment.duration(currentTime.diff(this.startTime));
    const time = this.toString(diffTime.minutes()) + ':' + this.toString(diffTime.seconds());
    this._recordingTime.next(time);
  },
  1000
 );
}

 private toString(value) {
   let val = value;
   if (!value) {
   val = '00';
 }
 if (value < 10) {
   val = '0' + value;
 }
 return val;
}

stopRecording() {
  if (this.recorder) {
    this.recorder.stop((blob) => {
      if (this.startTime) {
        const mp3Name = encodeURIComponent('audio_' + new Date().getTime() + '.mp3');
        this.stopMedia();
        this._recorded.next({ blob: blob, title: mp3Name });
      }
     }, () => {
       this.stopMedia();
       this._recordingFailed.next();
     });
  }
} 

 private stopMedia() {
   if (this.recorder) {
     this.recorder = null;
     clearInterval(this.interval);
     this.startTime = null;
     if (this.stream) {
       this.stream.getAudioTracks().forEach(track => track.stop());
       this.stream = null;
     }
   }
 }

1 个答案:

答案 0 :(得分:1)

请尝试以下操作:

stopRecording() {
    if (this.isRecording) {
        var that = this;
        this.audioRecordingService.stopRecording(function() {
            that.ccc.blob = that.audioRecordingService.getBlob();
            stopRecording(); // this line is tricky; maybe "that.stopRecording()"?
        });
        this.isRecording = false;
        return;
    }

    var reader = new FileReader();
    reader.readAsDataURL(this.ccc.blob);
    reader.onloadend = function() {
        console.log("onloadend")
        var base64data = reader.result;
        localStorage.setItem("audioData", base64data.toString());
    }
    var data = localStorage.getItem("audioData");
    var clean_data = data.substr(data.indexOf(',') + 1);
    var post_obj = JSON.stringify({
        "name": "audio",
        "base64": clean_data
    })
    this.commandList.postBlob(post_obj).subscribe((res) => {
        console.log("Google API translation: " + res["res"]);
    });
}

即我在您的代码中对此进行了更改:

audioRecordingService.stopRecording(function() {
    var blob = audioRecordingServices.getBlob();
});