gpt4 book ai didi

javascript - 删除 createMediaElementSource

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:14:28 26 4
gpt4 key购买 nike

我已经为这个问题到处搜索,但找不到任何东西。我处于需要删除 source = 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')
}

因此,当我在运行 analyzerStop() 之后运行 analyzerInitialize() 时,我仍然会收到此错误:

audio.js:179 Uncaught DOMException: Failed to execute 'createMediaElementSource' on 'AudioContext': HTMLMediaElement already connected previously to a different MediaElementSourceNode

我怎样才能使 analyzerInitialize() 永远不会失败?

最佳答案

我遇到过同样的问题。不幸的是,我没有找到如何从音频元素中获取已创建的 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();
}

通过使用 WeakMap 我避免了内存问题。

关于javascript - 删除 createMediaElementSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35492397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com