无法读取null的属性'addEventListener'但是ID就在那里

时间:2014-12-28 02:47:05

标签: javascript web-audio

我想使用网络音频API并进行音频可视化。

我跟随此tutorial,但我收到此错误:

Cannot read property 'addEventListener' of null

在这部分代码中:

audioElement.addEventListener("canplay", function() {
var source = context.createMediaElementSource(audioElement);
source.connect(context.destination);

});

我确实在html中有一个名为player的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();
    });

});

1 个答案:

答案 0 :(得分:2)

您有一个初始化函数($(document).ready的回调),但您在函数外部初始化audioElement,因此元素将不会准备就绪。您应该在初始化函数之外声明元素,但在初始化函数内初始化它。