使用canvas+web audio制作动态音频时出现Failed to execute 'createMediaElementSource' on 'AudioContext': HTMLMediaElement already connected previously to a different MediaElementSourceNode报错。该如何解决呢,代码如下:
<div class="player_page">
<canvas id="canvas">
</canvas>
</div>
```html
let ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let audioArray = [
'../music/1.mp3',
'../music/2.mp3',
'../music/3.mp3',
'../music/4.mp3',
'../music/4.mp3',
'../music/4.mp3',
'../music/4.mp3',
'../music/4.mp3'
];
let audioNum = 0;
let oAudio = document.getElementById('music_mp3');
oAudio.crossOrigin = 'anonymous';
oAudio.src = audioArray[audioNum];
// 获取canvas元素宽高
let WIDTH = canvas.width;
let HEIGHT = canvas.height;
let Play=document.getElementById('play');
Play.onclick=function(){
let oCtx = new AudioContext();
let audioSrc = oCtx.createMediaElementSource(oAudio);
let analyser=oCtx.createAnalyser();
audioSrc.connect(analyser);
analyser.connect(oCtx.destination);
analyser.fftSize=512;
let bufferLength=analyser.frequencyBinCount;
let dataArray=new Uint8Array(bufferLength);
let barWidth=(WIDTH/bufferLength)-1;
let barHeight;
function draw(){
analyser.getByteFrequencyData(dataArray);
let x=0;
ctx.clearRect(0,0,WIDTH,HEIGHT);
for(let i=0;i<bufferLength;i++){
barHeight=dataArray[i];
ctx.fillStyle='rgb(228,255,255)';
ctx.fillRect(x,HEIGHT,barWidth,-barHeight);
x+=barWidth+1;
}
window.requestAnimationFrame(draw);
};
draw();
}