Seb*_*sen 7 javascript mediaelement
我已经为这个问题到处谷歌,但找不到任何东西。我处于需要删除 asource = createMediaElementSource以便我可以再次创建它的情况。我正在使用音频分析器,每次使用 ajax 加载指定曲目时都必须加载它。一旦你转到另一个页面,然后返回,分析器就消失了。因此我需要以某种方式重新初始化它。
我的代码:
var analyserElement = document.getElementById('analyzer');
var canvas, ctx, source, context, analyser, fbc_array, bars, bar_x,
bar_width, bar_height;
function analyzerSetElements() {
var analyserElement = document.getElementById('analyzer');
}
function analyzerInitialize() {
if (context == undefined) {
context = new AudioContext();
}
analyser = context.createAnalyser();
canvas = analyserElement;
ctx = canvas.getContext('2d');
source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
frameLooper();
}
function analyzerStop(){
context = undefined;
analyser = undefined;
source = undefined;
}
function frameLooper() {
canvas.width = canwidth;
canvas.height = canheight;
ctx.imageSmoothingEnabled = false;
fbc_array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fbc_array);
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
ctx.fillStyle = "white"; // Color of the bars
function valBetween(v, min, max) {
return (Math.min(max, Math.max(min, v)));
}
var beatc = fbc_array[2] / 4;
var beatround = Math.round(beatc);
//if (beatround < 10) {
// ctx.globalAlpha = '0.1125';
//}
//else {
// ctx.globalAlpha = '0.' + beatround;
//}
bars = canbars;
for (var i = 0; i < bars; i += canmultiplier) {
bar_x = i * canspace;
bar_width = 2;
bar_height = -3 - (fbc_array[i] / 2);
ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
}
window.requestAnimationFrame(frameLooper);
console.log('Looped')
}
Run Code Online (Sandbox Code Playgroud)
因此,当我运行analyzerInitialize()后运行时,analyzerStop()我仍然收到此错误:
audio.js:179 未捕获的 DOMException:无法在“AudioContext”上执行“createMediaElementSource”:HTMLMediaElement 之前已连接到不同的 MediaElementSourceNode
我怎样才能让它运行analyzerInitialize()永远不会失败?
小智 4
我也遇到过同样的问题。MediaElementSourceNode不幸的是我没有找到如何从音频元素创建。尽管如此,可以通过使用WeakMap记住来解决这个问题MediaElementSourceNode:
var MEDIA_ELEMENT_NODES = new WeakMap();
function analyzerInitialize() {
if (context == undefined) {
context = new AudioContext();
}
analyser = context.createAnalyser();
canvas = analyserElement;
ctx = canvas.getContext('2d');
if (MEDIA_ELEMENT_NODES.has(audio)) {
source = MEDIA_ELEMENT_NODES.get(audio);
} else {
source = context.createMediaElementSource(audio);
MEDIA_ELEMENT_NODES.set(audio, source);
}
source.connect(analyser);
analyser.connect(context.destination);
frameLooper();
}
Run Code Online (Sandbox Code Playgroud)
通过使用WeakMap我可以避免内存问题。
| 归档时间: |
|
| 查看次数: |
4467 次 |
| 最近记录: |