Cut and Paste audio using web audio api and wavesurfer.js

前端 未结 2 1484
小鲜肉
小鲜肉 2021-02-01 11:14

I am currently trying to make a web editor allowing users to easily adjust basic settings to their audio files, as a plugin I\'ve integrated wavesurfer.js as it has a very neat

相关标签:
2条回答
  • 2021-02-01 11:36

    Interesting question. First word that comes to mind is ffmpeg. I can't talk from experience but if I was trying to achieve this I would approach it like:

    Let's assume you select a region of your audio track and you want to copy it and make a new track out of it (later maybe just appending it to an existing track).

    1. Use the getSelection() method provided by the nice wavesurfer.js library. This will give you startPosition() and endPosition()[in seconds].
    2. Given those points you now can use ffmpeg on the backend to select the region and save it as a new file (eventually upload it to S3,etc.). See this thread to get an idea of how to call ffmpeg from your ruby app (the commandline parameters shown there can be helpful too).

    Note that if you plan to copy and paste many regions to piece up a new track, making this in the backend all the time will probably make no sense, and I guess I'd try to look for a client-side JS approach.

    I hope this is helpful at least for an easy use case, and gets you started for the rest ;)

    Update This might be worth reading.

    • Web Audio API, tutorial here.
    • HTML5 audio - State of play. here(don't miss the section on TimeRanges, looks like a reasonable option to try).
    • This one(Outdated, but worth a look, interesting links).
    0 讨论(0)
  • 2021-02-01 11:38

    Reading this answer suggests you can create an empty AudioBuffer of the size of the audio segment you want to copy (size = length in seconds ⨉ sample rate), then fill its channel data with the data from the segment.

    So the code might be like this:

    var originalBuffer = wavesurfer.backend.buffer;
    var emptySegment = wavesurfer.backend.ac.createBuffer(
        originalBuffer.numberOfChannels,
        segmentDuration * originalBuffer.sampleRate,
        originalBuffer.sampleRate
    );
    for (var i = 0; i < originalBuffer.numberOfChannels; i++) {
        var chanData = originalBuffer.getChannelData(i);
        var segmentChanData = emptySegment.getChannelData(i);
        for (var j = 0, len = chanData.length; j < len; j++) {
            segmentChanData[j] = chanData[j];
        }
    }
    
    emptySegment; // Here you go!
                  // Not empty anymore, contains a copy of the segment!
    
    0 讨论(0)
提交回复
热议问题