无法读取 null 的属性“addEventListener”---但 ID 在那里
Cannot read property 'addEventListener' of null--- But ID is there
我想使用网络音频API并制作音频可视化。
我遵循本教程,但我收到此错误:
Cannot read property 'addEventListener' of null
在代码的这一部分中:
audioElement.addEventListener("canplay", function() {
var source = context.createMediaElementSource(audioElement);
source.connect(context.destination);
});
我在 html 中确实有一个名为播放器的 id,如下所示:
<audio id="player" src="tune.wav"></audio>
我的完整代码是这样的:
var context = new AudioContext(); // Create audio container
var request = new XMLHttpRequest();
var dataArray = new Float32Array(bufferLength);
var analyser = context.createAnalyser();
analyser.smoothingTimeConstant = 0.3;
analyser.fftSize = 1024;
analyser.getFloatFrequencyData(dataArray);
var bufferLength = analyser.frequencyBinCount;
var audioElement = document.getElementById("player");
audioElement.addEventListener("canplay", function() {
var source = context.createMediaElementSource(audioElement);
source.connect(context.destination);
});
function start(){
request.open("GET", "tune.wav", true);
request.responseType = "arraybuffer"; // Read as binary data
request.onload = function(){
var data = request.response;
audioRouting(data);
};
request.send();
}
function stop() {
source.stop(context.currentTime); // stop the source immediately
}
// Create Buffered Sound Source
function audioRouting(data) {
source = context.createBufferSource(); // Create sound source
context.decodeAudioData(data, function(buffer){ // Create source buffer from raw binary
source.buffer = buffer; // Add buffered data to object
source.connect(context.destination); // Connect sound source to output
playSound(source); // Pass the object to the play function
});
}
// Tell the Source when to play
function playSound() {
source.start(context.currentTime); // play the source immediately
}
console.log();
$( document ).ready(function() {
$( ".play" ).click(function() {
start();
console.log("yo");
});
$( ".stop" ).click(function() {
stop();
});
});
你有一个初始化函数($(document).ready
的回调),但你在函数之外初始化audioElement
,因此元素不会准备好。 相反,您应该在初始化函数外部声明元素,但在初始化函数中对其进行初始化。
相关文章:
- 通过知道对象的id在JSON中查找对象
- 使用类而不是id在JavaScript中隐藏显示
- 如何使用 html 类或 id 在任何地方显示内容
- 使用范围作为 id 在传单中创建地图
- EmberJS没有找到任何模型,但它'在那里
- 如何在单击按钮后提取javascript中textarea的id(在本例中是动态的)
- Datepicker克隆ID在添加行时保持不变
- 我希望我的id在用户点击按钮时抖动
- 关于在动态创建的元素中添加预先样式化的类或在那里添加stying&然后
- 如何检查id(在id列表中)是否存在于具有id的对象数组中
- Ember更新id在服务器上持久化后
- 角度 - 动态 ng 模型名称,ID 在 ng 重复中
- 如何制作自适应块并在那里添加块
- id:在续集中创建新项目时为空
- 如何使用代码点火器根据传递的 ID 在引导模式中加载视图
- 嘿,在那里寻找解决方案
- 如何使鼠标输入功能具有淡入淡出效果并保持在那里
- 我可以控制台.debug()并在那里制作Chrome Dev-tools断点吗?
- 无法读取 null 的属性“addEventListener”---但 ID 在那里
- 导航到另一个页面,在那里显示书签/id,同时隐藏其他