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

徘徊边缘 提交于 2019-12-02 22:54:30
katspaugh

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!
lllllll

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).
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!