编程语言
首页 > 编程语言> > javascript – 如何在Web音频API中反向播放,同时保留正向版本?

javascript – 如何在Web音频API中反向播放,同时保留正向版本?

作者:互联网

据我所知,Google Chrome(v21)中的Web Audio API不支持以下内容:

    source.playbackRate.value = -1; 

我非常希望!我会耐心等待,但与此同时,this post有一个不错的替代解决方案.我已经采用它试图反转我自己从loaded bufferlist加载的音频样本,希望我可以同时拥有每个加载缓冲区的正向和反向版本,如下所示:

    function finishedLoading(bufferList)  {
        for (var it = 0; it < this.urlList.length; ++it) {  
            storedBuffer[it] = bufferList[it]; // assign bufferList to globals
            storedBufferR[it] = bufferList[it];

            // attempt to reverse storedBufferR only ...
            Array.prototype.reverse.call( storedBufferR[it].getChannelData(0) );
            Array.prototype.reverse.call( storedBufferR[it].getChannelData(1) ); 
        }
    }

上面的函数确实会反转回放,但它会反转’storedbufferR’和’storedbuffer’,这样所有的缓冲区都会反转!

所以这就是我迷路的地方……我明白Array.protoype会影响所有数组,所以我想我可以看到’storedBuffer’对’storedBuffer’的反向方法是如何影响的.编辑:反向方法只影响有问题的数组

但是有可能重写上面的函数以确保array.protoype只影响我想要反转的存储缓冲区吗?如果没有,还有另一种方法可以存储正向和反向版本吗?

解决方法:

关于共享相同引用的两个AudioBuffers的评论是在正确的轨道上,但解决方案不是创建一个新的AudioContext;相反,你只需要创建一个新的AudioBuffer并克隆包含实际音频样本的底层Float32Arrays.

例如,此函数将克隆AudioBuffer:

function cloneAudioBuffer(audioBuffer){
    var channels = [],
        numChannels = audioBuffer.numberOfChannels;

    //clone the underlying Float32Arrays
    for (var i = 0; i < numChannels; i++){
        channels[i] = new Float32Array(audioBuffer.getChannelData(i));
    }

    //create the new AudioBuffer (assuming AudioContext variable is in scope)
    var newBuffer = context.createBuffer(
                        audioBuffer.numberOfChannels,
                        audioBuffer.length,
                        audioBuffer.sampleRate
                    );

    //copy the cloned arrays to the new AudioBuffer
    for (var i = 0; i < numChannels; i++){
        newBuffer.getChannelData(i).set(channels[i]);
    }

    return newBuffer;
}

然后,修改上面的……

function finishedLoading(bufferList)  {
    for (var it = 0; it < this.urlList.length; ++it) {  
        storedBuffer[it] = bufferList[it]; // assign bufferList to globals
        storedBufferR[it] = cloneAudioBuffer(bufferList[it]);

        // attempt to reverse storedBufferR only ...
        Array.prototype.reverse.call( storedBufferR[it].getChannelData(0) );
        Array.prototype.reverse.call( storedBufferR[it].getChannelData(1) ); 
    }
}

标签:javascript,html5,google-chrome,web-audio,audiobuffer
来源: https://codeday.me/bug/20190901/1785659.html