我正在用HTML5和Javascript制作游戏。
如何通过Javascript播放游戏音频?
我正在用HTML5和Javascript制作游戏。
如何通过Javascript播放游戏音频?
Just use this:
<video controls="" autoplay="" name="media"><source src="Sound URL Here" type="audio/mpeg" /></video>
Or, to make it simpler:
<video controls="" autoplay="" name="media">
<source src="Sound URL Here" type="audio/mpeg" />
</video>
Sample:
<video controls="" autoplay="" name="media">
<source src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3" type="audio/mpeg">
</video>
Have NO IDEA if this works on other browsers other than Chrome 73!!
This is some JS i came up with on a baby AI project im working with. i hope this is able to help you out.
<!DOCTYPE html>
<html>
<head>
<title>
js prompt AI
</title>
<style>
#button {
border: 1px solid black;
border-radius: 10px;
font-size: 22px;
height:65px;
width:100px;
text-align: center;
line-height: 65px;
}
</style>
</head>
<body>
<audio id="myAudio" src="./how_are_you.m4a"></audio>
<p>To Interact with the AI please click the button</p>
<div id=button>click</div>
<script>
var button = document.getElementById("button");
function playBack() {
button.addEventListener("click", function (){
var talk = prompt("If you wish for the AI to respond type hi");
var myAudio = document.getElementById("myAudio");
if(talk === "hi") {
myAudio.play();
}
}) ;
}
playBack();
</script>
</body>
</html>
if you want to play your audio whenever the page is opened then do like this.
<script>
function playMusic(){
music.play();
}
</script>
<html>
<audio id="music" loop src="sounds/music.wav" autoplay> </audio>
</html>
and call this playMusic() whenever you need in your game code.
这是一个很老的问题,但是我想添加一些有用的信息。话题开始者提到他是"making a game"
。因此对于每个需要音频进行游戏开发的人来说,有一个更好的选择,不仅仅是<audio>
标签或标签HTMLAudioElement
。我认为您应该考虑使用Web Audio API:
尽管网络音频不再需要插件,但音频标签为实现复杂的游戏和交互式应用程序带来了明显的限制。Web Audio API是用于处理和合成Web应用程序中音频的高级JavaScript API。该API的目标是包括现代游戏音频引擎中的功能以及现代桌面音频制作应用程序中的某些混合,处理和过滤任务。
With the security requirements that a user must interact with a webpage for audio to be allowed this is how I do it, based on reading many articles, including on this site
Because all the audio files have been "played" on the same OnClick, you can now play them any time in the game without restrictions
Note that for best compatability do not use wav files, MS do not support them
Use mp3 and ogg, that covers all devices
Example:
repeat as needed for all audio in the game
Then:
repeat as needed except do not pause the audio you want to hear when the game starts