最近B站有个很火的游戏,叫做倒放挑战。规则很绕,这里就不详细说了,过几天再写个完整的倒放游戏项目出来。今天先解释一下在web中音频倒放的原理。
在这里面最重要的就是Array.prototype.reverse()
。这个方法可以将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。注意,该方法会改变原数组。
示例:
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]
const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]
/* Careful: reverse is destructive. It also changes
the original array */
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]
那么,在处理音频的时候我们该如何使用Array.prototype.reverse()
呢。关键在于通过Float32Array
获取AudioBuffer
中每个通道的音频数据矩阵,然后将它反转。下面通过一段简单的代码示例来帮助理解。
var context = new AudioContext(),
request = new XMLHttpRequest();
request.open('GET', 'path/to/audio.mp3', true);
request.responseType = 'arraybuffer';
request.addEventListener('load', function(){
context.decodeAudioData(request.response, function(buffer){
var source = context.createBufferSource();
Array.prototype.reverse.call( buffer.getChannelData(0) );
Array.prototype