Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim an audio file using javascript (first 3 seconds)

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.

like image 784
Ahmed Ali Avatar asked Sep 01 '26 08:09

Ahmed Ali


1 Answers

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();
like image 161
Stuart Wakefield Avatar answered Sep 03 '26 00:09

Stuart Wakefield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!