gpt4 book ai didi

Javascript Web Audio API AnalyserNode 不工作

转载 作者:行者123 更新时间:2023-11-30 13:03:21 28 4
gpt4 key购买 nike

代码应该流式传输任何 url 并提供音频的可视化。不幸的是,可视化工具无法正常工作。可视化依赖于来自 AnalyzerNode 的数据,它总是返回空数据。为什么这段代码中的 AnalyserNode 不起作用?源节点上的 numberOfOutputs 在我 .connect() 之后增加,但 AnalyserNode 上的 numberOfInputs 没有改变。

<html>
<head>
<script>
var context;
var source;
var analyser;
var canvas;
var canvasContext;

window.addEventListener('load', init, false);
function init() {
try {
// Fix up for prefixing
window.AudioContext = window.AudioContext || window.webkitAudioContext;

window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

context = new AudioContext();
analyser = context.createAnalyser();
canvas = document.getElementById("analyser");
canvasContext = canvas.getContext('2d');
}
catch(e) {
alert(e);
alert('Web Audio API is not supported in this browser');
}
}

function streamSound(url) {
var audio = new Audio();
audio.src = url;
audio.controls = true;
audio.autoplay = true;
source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
document.body.appendChild(document.createElement('br'));
document.body.appendChild(audio);
render();
}

function render(){
window.requestAnimationFrame(render);
//Get the Sound data
var freqByteData = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(freqByteData);
//we Clear the Canvas
canvasContext.clearRect(0, 0, canvas.width, canvas.height);
//draw visualization
for(var i=0;i<analyser.frequencyBinCount;i++){
canvasContext.fillRect(i*2,canvas.height,1,-freqByteData[i]);
//Data seems to always be zero
if(freqByteData[i] != 0) {
alert(freqByteData[i]);
}
}
}
</script>
</head>
<body>
<button onclick="streamSound(document.getElementById('url').value)"> Stream sound</button>
<input id="url" size='77' value="Enter a URL to Stream">
<br />
<canvas id="analyser" width="600" height="200"></canvas>
</body>
</html>

最佳答案

您应该为音频的 canplay 事件设置一个事件监听器,并且只设置 MediaElementSource 并在该事件触发后连接它。

它也是won't work in Safari due to a bug in their implementation . AFAIK Chrome 是唯一正确支持 Web Audio API 的浏览器。

关于Javascript Web Audio API AnalyserNode 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16600639/

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