点击播放音频

时间:2015-05-01 18:30:24

标签: javascript html audio onclick

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



// 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>
&#13;
&#13;
&#13;

我试图看看是否需要让声音充当变量,然后每个变量都可以插入到不同的变量(shootButton,unloadButton和reloadButton)中,或者我必须做一些完全独立的事情?

2 个答案:

答案 0 :(得分:1)

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

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

如果你有声音,你可以把它们放在你的代码之间:

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

我希望我能回答你的问题。

答案 1 :(得分:0)

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

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

Getting Started with Web Audio API