使用.play()的动态声音文件

Dynamic sound file with .play()

本文关键字:动态 声音 文件 play 使用      更新时间:2023-09-26

我正在创建的代码是一个函数,它应该与函数。play()它…下面是代码

function playSound() {
document.getElementById('newMessage').play();
}
var sound = document.createElement('audio');
 sound.setAttribute("src","http://www.soundjay.com/button/beep-2.wav");
 sound.id="newMessage";
 sound.setAttribute('autoplay','false');
 document.body.appendChild(sound);

虽然每次在控制台尝试做playSound();它说playSound是未定义的。所以我试着做document.getElementById('newMessage').play();,它也不玩,也没有$('#newMessage').play();它带来了一个错误的对象[对象对象]没有方法播放。

任何建议,因为这是第一次尝试动态创建音频文件并使用函数来播放它。我看了一些其他的主题,他们似乎没有把我带到正确的方向。由于

我的猜测是您在页面已经加载后定义playSound方法,可能在一些onload方法中。如果是这种情况,请尝试将该方法附加到window对象:

window.playSound = function() {
  document.getElementById('newMessage').play();
} 

这是使函数可用,即使函数是在页面加载后定义的。另外,你不应该将自动播放设置为false。它的默认值是false,如果你想把它设置为true,你可以设置autoplay="autoplay"

JSFiddle