无法读取 null 的属性“addEventListener”---但 ID 在那里

Cannot read property 'addEventListener' of null--- But ID is there

本文关键字:ID 在那里 addEventListener 读取 null 属性      更新时间:2023-09-26

我想使用网络音频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,因此元素不会准备好。 相反,您应该在初始化函数外部声明元素,但在初始化函数中对其进行初始化。