Cut audio with javascript

Asked

Viewed 254 times

1

People need to cut an audio in the client-side and send the "cut" bytes to Nodejs. Is it possible? How can I implement?

  • 1

    Why not do this on Node.js? (curiosity, because it is much easier to manage files and ensure server-side processing)

  • @Sergio wanted the user not to have to send the complete file (a song) to the server. I wanted to let him cut the audio and send the size he wants. But the problem is I need to do it with JS, only JS. https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/createBuffer this link contains an example of creating an empty audio buffer and then filling it. My theory would be to open the file go through the bytes and catch an interval then send to Node.js, but I don’t know how to implement.

1 answer

2

Well, I managed to solve my problem and I came back here to share the solution with someone who in the future also needs it. 'Cause I couldn’t find anything like it on the Net no matter how amazing it seems.

Vanillajs

window.onload = function (){
  'use strict';

   var xhr = new XMLHttpRequest();
    xhr.open("GET",'path/da/musica', true);
    xhr.responseType = "arraybuffer";

    xhr.onload = function (e) {
        var blob    = new Blob([xhr.response], {type: "audio/mp3"});
        var newBlob = new Blob([blob.slice(/*Início em bytes*/, /*Fim em bytes*/)],    {type:"audio/mp3"});

        var reader = new FileReader();
            reader.onload = function(){

            var dataURL = reader.result;
            var output = document.getElementById('audio');
            output.src = dataURL;
            output.autoplay = true;
       };

        reader.readAsDataURL(newBlob);

    }

    xhr.send(null);
}

HTML

<audio id="audio"></audio>

Note: I did not use myself in the most orthodox way, but it is functional

  • I believe you will have problems if the MP3 has been topped with VBR (Variable Bit Rate encoding), in this case it is not possible to predict the initial and final position, after all the bitrate will not be constant, so you will need to require or verify that the MP3 be encoding using CBR (Constant Bit Rate encoding).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.