我正在建立一个网站,并希望在页面刷新时加载MP3文件,但是某种程度上它无法播放。
<body>
<audio id="kofi" autoplay="autoplay">
<source src="kofi.mp3" type="audio/mp3">
</audio>
<script type="text/javascript">
window.onload = function(){
document.getElementById('kofi').play(); // On this line I get error "Uncaught (in promise) DOMException"
}
</script>
<body>
答案 0 :(得分:3)
play()/ pause()功能正在使用Promises,这就是为什么它不能按您期望的那样工作。通过this reference,我可以举以下例子:
<script>
window.onload = function() {
var song = document.getElementById('kofi');
// This will allow us to play song later...
song.load();
fetchSongAndPlay();
}
function fetchSongAndPlay() {
fetch('kofi.mp3')
.then(response => response.blob())
.then(blob => {
song.srcObject = blob;
return song.play();
})
.then(_ => {
// Music playback started ;)
})
.catch(e => {
// Music playback failed ;(
})
}
</script>