Web音频api意外的语法标记,声音不会播放

时间:2014-12-24 13:48:50

标签: javascript web-audio

我得到了这个"未捕获的TypeError:无法读取属性' addEventListener' of nullaudioStuff.js:39(匿名函数)"

在这一行:

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

我不明白,语法对我来说似乎没问题,任何想法?

我通过端口8000中带有ruby的服务器运行应用程序我开始使用以下代码:

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

这是完整的代码:



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);




1 个答案:

答案 0 :(得分:2)

你必须在页面加载后添加事件监听器 因此document.querySelector('.play')返回null,因此错误为Uncaught TypeError: Cannot read property 'addEventListener' of nullaudioStuff.js:39 (anonymous function)

没有发现元素播放'类。

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