1 回答
TA贡献1895条经验 获得超7个赞
我认为这是因为控制台中的此错误
js:47 AudioContext 不允许启动。它必须在用户在页面上做出手势后恢复(或创建)。
如果您引用消息中的链接,则它指定
如果您在页面加载时创建 AudioContext,则必须在用户与页面交互(例如,用户单击按钮)后的某个时间调用resume()。或者,如果在任何附加节点上调用 start(),则 AudioContext 将在用户手势后恢复。
由于您AudioContext
是在用户手势(单击)之前创建的,因此您可以修改begin
函数以恢复上下文,
function begin()
{
context.resume().then(() => {
audio.play();
requestAnimationFrame(drawCanvas);
});
};
工作演示:
let frequencyArray = [];
let analyser;
let request;
var flag=0;
var height=0;
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const bars = Math.round(canvas.width);
const lineWidth = 3;
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
const audio = new Audio();
audio.src =
"https://s3.us-west-2.amazonaws.com/storycreator.uploads/ck9kpb5ss0xf90132mgf8z893?client_id=d8976b195733c213f3ead34a2d95d1c1";
audio.crossOrigin = "anonymous";
audio.load();
const context = new (window.AudioContext || window.webkitAudioContext)();
analyser = context.createAnalyser();
const source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
frequencyArray = new Uint8Array(analyser.frequencyBinCount);
function begin()
{
context.resume().then(() => {
audio.play();
requestAnimationFrame(drawCanvas);
})
};
function end()
{
cancelAnimationFrame(request);
audio.pause();
};
audio.addEventListener("ended", close);
function close()
{
if(flag==0)
{
flag=1;
}
else
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
flag=0;
}
}
const drawCanvas = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
analyser.getByteTimeDomainData(frequencyArray);
for (var i = 0; i < bars; i+=5) {
height = frequencyArray[i] * 0.25;
drawLine(
{
i,
bars,
height
},
canvas,
ctx
);
}
if(flag==0)
{
request = requestAnimationFrame(drawCanvas);
}
else
{
flag=2;
close();
}
};
const drawLine = (opts, canvas, ctx) => {
const { i, bars, height } = opts;
// draw the bar
ctx.strokeStyle = "#212121";
ctx.lineWidth = lineWidth;
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(i, centerY);
ctx.lineTo(i, centerY + height);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(i, centerY);
ctx.lineTo(i, centerY - height);
ctx.stroke();
};
<!DOCTYPE html>
<html>
<head>
<body>
<button onClick=begin()>Start</button>
<button onClick=end()>End</button>
<canvas id="myCanvas" width="500" height="200" style="border:1px solid #d3d3d3;">
</canvas>
</body>
</html>
添加回答
举报