5

I have a question that can I trim my audio file that is recorded via javascript? Like I want to trim the first 3 seconds. I recorded the audio file using p5.js and merged the recorded file with karaoke audio with AudioContext() and I want to trim it because of an unpleasant sound at the start.

Ahmed Ali
  • 1,908
  • 14
  • 28

1 Answers1

9

You will probably need to read the audio into an AudioBuffer using something like AudioContext.decodeAudioData(), plug the AudioBuffer into a AudioBufferSourceNode. Then you can skip the first 3 seconds using the offset parameter of AudioBufferSourceNode.start() and record the resulting output stream.

Example code:

var source = audioCtx.createBufferSource();
var dest = audioCtx.createMediaStreamDestination();
var mediaRecorder = new MediaRecorder(dest.stream);

var request = new XMLHttpRequest();
request.open('GET', 'your.ogg', true);
request.responseType = 'arraybuffer';

request.onload = function() {
  var audioData = request.response;
  audioCtx.decodeAudioData(
    audioData,
    function(buffer) {
      source.buffer = buffer;
      source.connect(dest);
      mediaRecorder.start();
      source.start(audioCtx.currentTime, 3);
      // etc...
    },
    function(e){ 
      console.log("Error with decoding audio data" + e.err);
    }
  );

}

request.send();
Stuart Wakefield
  • 6,294
  • 24
  • 35