How to cut an audio recording in JavaScript

3.7k Views Asked by At

Say I record audio from my microphone, using Recorder.js. How can I then trim/crop/slice/cut the recording? Meaning, say I record 3.5 seconds, and I want only the first 3 seconds. Any ideas?

1

There are 1 best solutions below

1
guest271314 On BEST ANSWER

You can stop the original recording at 3 seconds or use <audio> element, HTMLMediaElement.captureStream() and MediaRecorder to record 3 seconds of playback of the original recording.

const audio = new Audio(/* Blob URL or URL of recording */);
const chunks = [];
audio.oncanplay = e => {
  audio.play();
  const stream = audio.captureStream();
  const recorder = new MediaRecorder(stream);
  recorder.ondataavailable = e => {
    if (recorder.state === "recording") {
      recorder.stop()
    };
    chunks.push(e.data)
  }
  recorder.onstop = e => {
    console.log(chunks)
  }
  recorder.start(3000);
}