user2643810
user2643810

Reputation:

Web audio api unexpected syntax token, Sound won't play

I get this " Uncaught TypeError: Cannot read property 'addEventListener' of nullaudioStuff.js:39 (anonymous function)"

In this line :

document.querySelector('.play').addEventListener('click', start); 

I dont understand, the syntax seems to be ok for me, any ideas ?

Im running the app through a server with ruby in port 8000 i started with this code :

ruby -r webrick -e "s = WEBrick::HTTPServer.new(:Port => 8000, :DocumentRoot => Dir.pwd); trap('INT') { s.shutdown }; s.start"

This is the full code:

function stop(){ 
    source.stop(context.currentTime); // stop the source immediately 
}

// Load the Sound with XMLHttpRequest 
function start() { 
// Note: this will load asynchronously 
var request = new XMLHttpRequest(); 
request.open("GET", tune.wav, true); request.responseType = "arraybuffer"; // Read as binary data  

// Asynchronous callback 
request.onload = function() { 
var data = request.response;  
audioRouting(data);
};  

request.send(); 
}


// 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 
  }



document.querySelector('.play').addEventListener('click', start); 
document.querySelector('.stop-button').addEventListener('click', stop);

Upvotes: 0

Views: 233

Answers (1)

Ajinkya Pisal
Ajinkya Pisal

Reputation: 591

you have to add event listener after page has been loaded.
Hence document.querySelector('.play') is returning null and hence the error
Uncaught TypeError: Cannot read property 'addEventListener' of nullaudioStuff.js:39 (anonymous function)

It is not finding elememt 'play' class.

$(document).ready(funtion(){
  document.querySelector('.play').addEventListener('click', start); 
  document.querySelector('.stop-button').addEventListener('click', stop);
});

Upvotes: 2

Related Questions