closeio / mic-recorder-to-mp3

Microphone Recorder to mp3
MIT License
244 stars 137 forks source link

How to implement pause functionality? #17

Open 318097 opened 4 years ago

buzinas commented 4 years ago

Currently there is no way to pause a recording. That said, we would be glad to accept PRs for that, it shouldn't be very difficult.

picasocro1 commented 4 years ago

I'm also interested in that too!

picasocro1 commented 4 years ago

I've prepared PR for that feature :)

anirket commented 3 years ago

Hi, when will this PR be merged?

martelman commented 1 month ago

@anirket just implement this.


    function MicRecorder(config) {
      classCallCheck(this, MicRecorder);

      this.config = {
        bitRate: 128,
        startRecordingAt: 300,
        deviceId: null,
        ...config
      };

      this.activeStream = null;
      this.context = null;
      this.microphone = null;
      this.processor = null;
      this.startTime = 0;
      this.isPaused = false; // Flag to track pause state
      this.isRecording = false; // Flag to track recording state

      this.lameEncoder = new Encoder(this.config);
    }

    createClass(MicRecorder, [{
      key: 'start',
      value: function start() {
        const AudioContext = window.AudioContext || window.webkitAudioContext;
        this.context = new AudioContext();
        this.config.sampleRate = this.context.sampleRate;

        const audioConstraints = this.config.deviceId
          ? { deviceId: { exact: this.config.deviceId } }
          : { audio: true };

        return navigator.mediaDevices.getUserMedia(audioConstraints)
          .then(stream => {
            this.activeStream = stream;
            this.isPaused = false;
            this.isRecording = true;
            this.addMicrophoneListener(stream);
            return stream;
          })
          .catch(err => {
            console.error('Error accessing microphone:', err);
            throw err;
          });
      }
    }, {
      key: 'addMicrophoneListener',
      value: function addMicrophoneListener(stream) {
        const _this = this;

        this.timerToStart = setTimeout(() => {
          delete _this.timerToStart;
        }, this.config.startRecordingAt);

        this.microphone = this.context.createMediaStreamSource(stream);
        this.processor = this.context.createScriptProcessor(0, 1, 1);

        this.processor.onaudioprocess = function (event) {
          if (_this.isPaused || !_this.isRecording) {
            return;
          }

          if (_this.timerToStart) {
            return;
          }

          const inputBuffer = event.inputBuffer.getChannelData(0);
          _this.lameEncoder.encode(inputBuffer);
        };

        this.microphone.connect(this.processor);
        this.processor.connect(this.context.destination);
      }
    }, {
      key: 'pause',
      value: function pause() {
        if (!this.isRecording) return;

        this.isPaused = true;
        console.log('Recording paused.');
      }
    }, {
      key: 'resume',
      value: function resume() {
        if (!this.isRecording) return;

        this.isPaused = false;
        console.log('Recording resumed.');
      }
    }, {
      key: 'stop',
      value: function stop() {
        if (this.processor && this.microphone) {
          this.microphone.disconnect();
          this.processor.disconnect();

          if (this.context && this.context.state !== 'closed') {
            this.context.close();
          }

          this.processor.onaudioprocess = null;
        }

        if (this.activeStream) {
          this.activeStream.getAudioTracks().forEach(track => track.stop());
          this.activeStream = null;
        }

        this.isRecording = false;
        this.isPaused = false;

        return this;
      }
    }, {
      key: 'getMp3',
      value: function getMp3() {
        return new Promise((resolve, reject) => {
          if (!this.lameEncoder) {
            reject(new Error('Encoder not initialized.'));
            return;
          }

          const finalBuffer = this.lameEncoder.finish();

          if (finalBuffer.length === 0) {
            reject(new Error('No audio data captured.'));
          } else {
            const mp3Blob = new Blob(finalBuffer, { type: 'audio/mp3' });
            resolve([finalBuffer, mp3Blob]);
            this.lameEncoder.clearBuffer();
          }
        });
      }
    }]);

    return MicRecorder;
  }();```
Vaibhav0220 commented 1 month ago

@anirket just implement this.

    function MicRecorder(config) {
      classCallCheck(this, MicRecorder);

      this.config = {
        bitRate: 128,
        startRecordingAt: 300,
        deviceId: null,
        ...config
      };

      this.activeStream = null;
      this.context = null;
      this.microphone = null;
      this.processor = null;
      this.startTime = 0;
      this.isPaused = false; // Flag to track pause state
      this.isRecording = false; // Flag to track recording state

      this.lameEncoder = new Encoder(this.config);
    }

    createClass(MicRecorder, [{
      key: 'start',
      value: function start() {
        const AudioContext = window.AudioContext || window.webkitAudioContext;
        this.context = new AudioContext();
        this.config.sampleRate = this.context.sampleRate;

        const audioConstraints = this.config.deviceId
          ? { deviceId: { exact: this.config.deviceId } }
          : { audio: true };

        return navigator.mediaDevices.getUserMedia(audioConstraints)
          .then(stream => {
            this.activeStream = stream;
            this.isPaused = false;
            this.isRecording = true;
            this.addMicrophoneListener(stream);
            return stream;
          })
          .catch(err => {
            console.error('Error accessing microphone:', err);
            throw err;
          });
      }
    }, {
      key: 'addMicrophoneListener',
      value: function addMicrophoneListener(stream) {
        const _this = this;

        this.timerToStart = setTimeout(() => {
          delete _this.timerToStart;
        }, this.config.startRecordingAt);

        this.microphone = this.context.createMediaStreamSource(stream);
        this.processor = this.context.createScriptProcessor(0, 1, 1);

        this.processor.onaudioprocess = function (event) {
          if (_this.isPaused || !_this.isRecording) {
            return;
          }

          if (_this.timerToStart) {
            return;
          }

          const inputBuffer = event.inputBuffer.getChannelData(0);
          _this.lameEncoder.encode(inputBuffer);
        };

        this.microphone.connect(this.processor);
        this.processor.connect(this.context.destination);
      }
    }, {
      key: 'pause',
      value: function pause() {
        if (!this.isRecording) return;

        this.isPaused = true;
        console.log('Recording paused.');
      }
    }, {
      key: 'resume',
      value: function resume() {
        if (!this.isRecording) return;

        this.isPaused = false;
        console.log('Recording resumed.');
      }
    }, {
      key: 'stop',
      value: function stop() {
        if (this.processor && this.microphone) {
          this.microphone.disconnect();
          this.processor.disconnect();

          if (this.context && this.context.state !== 'closed') {
            this.context.close();
          }

          this.processor.onaudioprocess = null;
        }

        if (this.activeStream) {
          this.activeStream.getAudioTracks().forEach(track => track.stop());
          this.activeStream = null;
        }

        this.isRecording = false;
        this.isPaused = false;

        return this;
      }
    }, {
      key: 'getMp3',
      value: function getMp3() {
        return new Promise((resolve, reject) => {
          if (!this.lameEncoder) {
            reject(new Error('Encoder not initialized.'));
            return;
          }

          const finalBuffer = this.lameEncoder.finish();

          if (finalBuffer.length === 0) {
            reject(new Error('No audio data captured.'));
          } else {
            const mp3Blob = new Blob(finalBuffer, { type: 'audio/mp3' });
            resolve([finalBuffer, mp3Blob]);
            this.lameEncoder.clearBuffer();
          }
        });
      }
    }]);

    return MicRecorder;
  }();```

where should i implement it

give me a proper code or guidance