我'被困了。我的问题是,我通过createAudioBuffer
初始化我的mp3文件,并希望将每个音频文件与我的分析器连接起来。但只有我设置了audioSource [i] .start();最后一首曲目将通过分析仪。如果按下标签上的播放按钮(或外部按钮),我希望每个音频文件都通过该分析器
有没有办法让这项工作?
这是我的代码:
var canvas, ctx, source, audioCtx, analyser, fbc_array, bars, bar_x, bar_width, bar_height;
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var invocation = new XMLHttpRequest();
analyser = audioCtx.createAnalyser();
function initSound(i, track){
canvas = document.getElementById('analyser_render');
ctx = canvas.getContext('2d');
var d = document,
audio = new Audio();
if (audio.canPlayType) {
// Currently canPlayType(type) returns: "", "maybe" or "probably"
var canPlayMp3 = !!audio.canPlayType && "" != audio.canPlayType('audio/mpeg');
}
trackSource = track.uri + '/stream?client_id=62fa6c34df7382c8dc444a18f4ff72b4';
audio.src = trackSource;
audio.controls = true;
audio.loop = false;
audio.autoplay = false;
audio.preload = "none";
audio.setAttribute('data-tracknumber', i+1);
$('<div class="audioWrapper"><div class="url"></div><img class="img" /><div class="controls"><button class="play-pause"></button></div></div>').appendTo('#audio_box').append(audio);
analyser.connect(audioCtx.destination);
fetchAudioAsset(trackSource, audioCtx, function( buffer ) {
audioSource = [];
audioSource[i] = audioCtx.createBufferSource();
audioSource[i].buffer = buffer;
audioSource[i].connect(audioCtx.destination);
audioSource[i].connect(analyser);
});
function fetchAudioAsset (path, audioCtx, callback) {
invocation.open('GET', path, true);
invocation.responseType = 'arraybuffer';
invocation.onload = function() {
if (invocation.readyState != 4) return;
audioCtx.decodeAudioData(invocation.response, function(buffer) {
callback && callback(buffer);
});
}.bind(this);
invocation.onprogress = function(ev) {
$('.loaded').width(((ev.loaded / ev.total) * 100) + '%');
};
fetchAudioAsset.request && fetchAudioAsset.request.abort();
fetchAudioAsset.request = invocation;
invocation.send();
};
soundVisualizer();
}
function soundVisualizer() {
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame;
requestAnimationFrame(soundVisualizer);
fbc_array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fbc_array);
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
ctx.fillStyle = '#00CCFF'; // Color of the bars
bars = 100;
for (var i = 0; i < bars; i++) {
bar_x = i * 3;
bar_width = 2;
bar_height = -(fbc_array[i] / 2);
//fillRect( x, y, width, height ) // Explanation of the parameters below
ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
}
}
答案 0 :(得分:1)
这似乎是一个问题,i
的值不是您在启动()节点时的想法。这不是Web Audio API问题,而是JavaScript问题。
您需要通过参数传递它,这样您才能实际访问全局值。