单击播放音频

having audio play on click

我试图让一些按钮与声音一起工作,但没有成功。对于我正在使用的页面,我将其设置为:

// javascript file for gun tutorial//
window.onload=function()
{
 var extraAmmo = 210;
 var maxAmmo = 30;
 var currentAmmo = maxAmmo;
 
 var extraAmmoHud = document.getElementById("extra-ammo");
 var currentAmmoHud = document.getElementById("current-ammo");
 
 var shootButton = document.getElementById("shoot-button");
 var unloadButton = document.getElementById("unload-button");
 var reloadButton = document.getElementById("reload-button");
  refreshScreen();
  
 shootButton.onclick=function()
 {
  if(currentAmmo > 0)
  {
   currentAmmo--;
   refreshScreen();
  }
 }
 unloadButton.onclick=function() 
 {
     if (currentAmmo > 0)
  {
            unloadTimer = setTimeout(unloadButton.onclick, 150)
         currentAmmo--;
         refreshScreen();
     } 
  else unloadTimer = null;
 }
 reloadButton.onclick=function()
 {
  var difference = getDifference();
  if(extraAmmo >= difference)
  {
   currentAmmo += difference;
   extraAmmo -= difference;
  }
  else
  {
   currentAmmo += extraAmmo;
   extraAmmo -= extraAmmo;
  }
  refreshScreen();
  
  function getDifference()
  {
   return maxAmmo -currentAmmo;
  }
 }
 function refreshScreen()
 {
  extraAmmoHud.innerHTML="Extra Ammo: " + extraAmmo;
  currentAmmoHud.innerHTML="Current Ammo: " + currentAmmo;
 }
}
<!DOCTYPE HTML>

<html>
<head>
<meta charset="UTF-8">
<title>Gun Tutorial</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script src="js/gun.js"></script>
<audio src="sounds/GunShot.mp3"></audio>
<audio src="sounds/GunShotFullAuto.mp3"></audio>
<audio src="sounds/GunCockingFast.wav"></audio>
</head>

<body>
 <div id="wrapper">
 <header id="header">
  <h1>Welcome to the Gun Show</h1>
 </header>
 <div id="content"></div>
 <form>
 <div id="boxobuttons">
  <input type="button" value="Shoot" id="shoot-button" />
  <input type="button" value="Unload" id="unload-button" />
  <input type="button" value="Reload" id="reload-button" />
 </div>
 
  <div id="ammo-count">
   <p id="current-ammo"></p>
   <p id="extra-ammo"></p>
  </div>
 </form>
 <footer>
 </footer>
 </div>
</body>
</html>

我正在尝试查看是否需要将声音作为一个变量,然后可以将每个单独的变量插入到不同的变量(shootButton、unloadButton 和 reloadButton)中,或者我是否需要做一些事情完全分开?

为什么不在 javascript 中加载声音?

例如:var gunshot = new Audio('GunShot.mp3');

如果你有自己的声音,你可以像这样将它们放在你的代码之间:

shootButton.onclick=function()
    {
        if(currentAmmo > 0)
        {
            currentAmmo--;
            gunshot.play();
            refreshScreen();
        }
    }

我希望我用这个回答了你的问题。

从这段代码中我不清楚你是如何尝试播放你的音频文件的。音频标签主要用于嵌入用户控制的媒体。

如果您正在对短音频文件进行幕后操作,我建议您直接使用网络音频 API,最好使用 bufferLoader 对象来提供您的音频。本文的前半部分涵盖了您需要了解的所有内容:

Getting Started with Web Audio API