我正在尝试遵循 Wes Bos 的 Javascript30 教程,但是当我尝试制作“Javascript Drum Kit”网站时,我无法播放任何声音。那里有适当的声音文件,但是当我按下按键尝试播放声音时,当我检查控制台时出现此错误消息:
jsdrumkit.html:66 - 未捕获( promise )DOMException:该元素没有受支持的源。
这是网站的 Javascript:
function playSound(e){
//querySelector() is just when you need a single return value
//audio[input] is an attribute selector, and it works just like its CSS counterpart.
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
if(!audio) return;
audio.currentTime = 0; //rewind the file to the start
audio.play(); //**line 66 in the site's code**
console.log(key);
key.classList.toggle('playing');
}
function removeTransition(e) {
if(e.propertyName !== 'transform') return; //skip if it's not a transform
this.classList.remove('playing');
}
const keys = document.querySelectorAll('.key');
keys.forEach(key => key.addEventListener('transitionend', removeTransition));
window.addEventListener('keydown', playSound);
如果我什至无法让 .play() 工作,我还缺少什么?
最佳答案
尝试在 Firefox 中播放。去年 Chrome 的更新导致播放音频时出现问题,涉及 promise 、部分内容等。我正在研究解决方案,但目前还没有找到,这里是信息:Audio from Icecast server not playing in Chrome
关于javascript - 调用 .play() 会产生 "Uncaught (in promise) DOMException: The element has no supported sources."错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45388147/