我的目标是在按下特定键(即按下的键上的字母)时播放声音,但没有html音频标签,并带有来自Web-Audio API的audioBuffers。 此处执行的示例是,作为arraySources项创建的audioBufferSourceNode在使用.start()函数时不会显示任何声音。不知道为什么
var myHeader = new Headers({
'accept':'audio/mpeg',
'cache-controle':'private',
});
var myInit = { method: 'GET',
headers: myHeader,
mode: 'cors',
cache:'default' };
var AudCtx = new AudioContext();
arrayRes=[];
arrayBuffers=[];
arraySources=[];
for (var i=0;i<26;i++){
fetch('./audio/abc'+(i+1)+'.mp3',myInit).then(function(response){
arrayRes.push(response);
console.log(response);
return response;
})
.then(function(response){
return response.arrayBuffer();
})
.then(function(buffer){
console.log(buffer);
return AudCtx.decodeAudioData(buffer);
})
.then(function(decodedData){
arrayBuffers.push(decodedData);
console.log(decodedData);
})
}
var count = 0;
window.addEventListener("keydown",function(e){
var keycode = e.keyCode;
var posiArray = e.keyCode-65;
if (keycode>=65 && keycode<=91){
console.log("keycode = "+keycode+" & posiArray = "+posiArray);
console.log("count = "+count);
arraySources[count] = AudCtx.createBufferSource();
arraySources[count].buffer = arrayBuffers[posiArray];
count++;
}
})
window.addEventListener("click",function(){
arraySources[count-1].start(0);
})
<!DOCTYPE html>
<html>
<head>
<title>web audio test</title>
<meta charset="UTF-8">
</head>
<body>
<script src="script.js"></script>
</body>
</html>
请看一下这个答案,它应该做您想要达到的目的:
How to make a Web Audio element sound instantly when pressed on mobile?