因此,为了使事情简单明了,我尝试将AudioContext和画布一起使用,以根据当前在网页上播放的歌曲显示动画正弦波。我从Voice-change-o-matic(可以在GitHub上轻松找到并且是公共领域)中的代码开始,然后删除了对我的目的多余的内容以及对某些行的修改:
// set up canvas context for visualizer
var canvas = document.querySelector('.visualizer');
var canvasCtx = canvas.getContext("2d");
var intendedWidth = document.querySelector('.wrapper').clientWidth;
canvas.setAttribute('width',intendedWidth);
var visualSelect = document.getElementById("visual");
var drawVisual;
// set up forked web audio context, for multiple browsers
// window. is needed otherwise Safari explodes
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
//set up the different audio nodes we will use for the app
var analyser = audioCtx.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
analyser.smoothingTimeConstant = 0.85;
// grab audio track via XHR for convolver node
var soundSource = audioCtx.createBufferSource();
ajaxRequest = new XMLHttpRequest();
ajaxRequest.open('GET', 'https://mdn.github.io/voice-change-o-matic/audio/concert-crowd.ogg', true);
ajaxRequest.responseType = 'arraybuffer';
ajaxRequest.onload = function() {
var audioData = ajaxRequest.response;
audioCtx.decodeAudioData(audioData, function(buffer) {
soundSource = buffer;
}, function(e){ console.log("Error with decoding audio data" + e.err);});
};
ajaxRequest.send();
playSound();
function playSound(buffer){
var source = audioCtx.createBufferSource();
source.buffer = buffer;
soundSource.connect(analyser);
analyser.connect(audioCtx.destination);
soundSource.start();
visualize();
}
// set up canvas context for visualizer
function visualize() {
WIDTH = canvas.width;
HEIGHT = canvas.height;
analyser.fftSize = 2048;
var bufferLength = analyser.fftSize;
console.log(bufferLength);
var dataArray = new Uint8Array(bufferLength);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
var draw = function() {
drawVisual = requestAnimationFrame(draw);
analyser.getByteTimeDomainData(dataArray);
canvasCtx.fillStyle = 'rgb(200, 200, 200)';
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
canvasCtx.lineWidth = 2;
canvasCtx.strokeStyle = 'rgb(20, 120, 60)';
canvasCtx.beginPath();
var sliceWidth = WIDTH * 1.0 / bufferLength;
var x = 0;
for(var i = 0; i < bufferLength; i++) {
var v = dataArray[i] / 128.0;
var y = v * HEIGHT/2;
if(i === 0) {
canvasCtx.moveTo(x, y);
} else {
canvasCtx.lineTo(x, y);
}
x += sliceWidth;
}
canvasCtx.lineTo(canvas.width, canvas.height/2);
canvasCtx.stroke();
};
draw();
}
很显然,该代码无法正常工作,并且在经过数小时的思考之后,我完全没有想法。运行时,代码不会给我任何错误,并且会绘制画布,但是听不到任何音乐,并且应该是正弦波的行仍然保持不变。有人看到我想念的东西吗?
预先感谢您的帮助!