【发布时间】:2022-01-28 13:04:15
【问题描述】:
我正在尝试遵循 Wes Bos 的 Javascript30 教程,但是当我尝试制作“Javascript Drum Kit”网站时,我无法播放任何声音。适当的声音文件在那里,但是当我按下按键尝试播放声音时,当我检查控制台时出现此错误消息:
jsdrumkit.html:66 - Uncaught (in promise) DOMException: The element has no supported sources.
这是网站的 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() 工作,我错过了什么?
【问题讨论】:
-
您使用的是哪个浏览器?也许您的浏览器缺少支持?您还应该检查浏览器支持的格式,例如在这里developer.mozilla.org/en-US/docs/Web/HTML/…
标签: javascript audio