sound effect in a html5 game - javascript

I'm trying to play sound effect in a game with each hit,but the sound sometimes play and others NOT !!
I'm using the next code :
<script>
var hitSound = new Audio();
function playEffectSound()
{
hitSound = document.getElementById('effects');
hitSound.loop = false;
hitSound.currentTime = 0;
hitSound.play();
}
</script>
<audio id="effects" hidden>
<source src="sound/mp3/effect.mp3" type="audio/mpeg">
<source src="sound/wav/effect.wav" type="audio/wav">
</audio>
any ideas ?

Whenever you are using audio tag try writing its script after audio tag ,If you write script before that audio tag it gives sometime problem in playing the audio,
i would recommend Write Script at the end of the page that's the standard way to write script.
http://jsfiddle.net/LyDWH/4/
<!DOCTYPE html>
<html>
<body>
<audio id="effects" hidden >
<source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
</audio>
<div onclick= "playEffectSound();">Horse Click Me..!</div>
</body>
<script>
var hitSound = new Audio();
function playEffectSound()
{
hitSound = document.getElementById('effects');
hitSound.currentTime = 0;
hitSound.play();
}
</script>
</html>
​

You could use the following code to play audio
function playEffectSound(sound) {
//Does the sound already exist?
if (document.getElementById(sound) != null) {
document.getElementById(sound).play();
return;
}
//Create elements
var audioElement = document.createElement("audio");
var sourceElement = document.createElement("source");
sourceElement.src = sound + ".mp3";
sourceElement.type = "audio/mpeg";
var sourceElementWave = document.createElement("source");
sourceElementWave.src = sound + ".wav";
sourceElementWave.type = "audio/wav";
//Add sources to audio
document.body.appendChild(sourceElementWave);
document.body.appendChild(audioElement);
audioElement.setAttribute("id", sound);
audioElement.appendChild(sourceElement);
audioElement.loop = false;
audioElement.currentTime = 0;
audioElement.play();
}
You can use it like this: playEffectSound("sounds/effect"); and it will either play sounds/effect.mp3 or sounds/effect.wav

try with each hit to add a new var sound and sound.play() and it will just work fine

Related

JavaScript play() function does not working in HTML viewer

I write a JavaScript APP and want to run it on my phone.
I found that JavaScript APP cannot just run in Chrome. So I download a HTML viewer APP. I used below:
https://play.google.com/store/apps/details?id=in.vineetsirohi.htmlreader&hl=zh_HK&gl=US
My code is follow:
<audio id="audio0" src="./audio/0.mp3"></audio>
<audio id="audio1" src="./audio/1.mp3"></audio>
<audio id="audio2" src="./audio/2.mp3"></audio>
<audio id="audio3" src="./audio/3.mp3"></audio>
<audio id="audio4" src="./audio/4.mp3"></audio>
<audio id="audio5" src="./audio/5.mp3"></audio>
<audio id="audio6" src="./audio/6.mp3"></audio>
<audio id="audio7" src="./audio/7.mp3"></audio>
<audio id="audio8" src="./audio/8.mp3"></audio>
<audio id="audio9" src="./audio/9.mp3"></audio>
<audio id="audio10" src="./audio/10.mp3"></audio>
<audio id="audio100" src="./audio/100.mp3"></audio>
<img src='./img/start.png' width='300px' onclick="startFunction()">
<div class="countingnumber" id="countingnumber"></div>
<script>
var count=0;
var speed=4;
var max=100;
function startFunction(){
count=0;
timer1();
}
function timer1(){
var timeout= speed*1000;
if(count<max){
count++;
document.getElementById("countingnumber").innerHTML = count;
play(count);
}
setTimeout(timer1, timeout);
}
function play(input){
var temp=input%10;
if (temp==0) temp=10;
if(input>10){
if(input>=100){
var temp=Math.floor(input/100);
var audio = document.getElementById("audio"+temp);
audio.play();
setTimeout(audio.pause,480);
setTimeout(playaudio, 500,"audio100");
if(input%100>=20){
setTimeout(play, 1000,input%100);
}
else if(input%100>=10){
setTimeout(playaudio, 1000,"audio1");
setTimeout(playaudio, 1500,"audio10");
setTimeout(play, 2000,input%10);
}
else if(input%100>0){
setTimeout(playaudio, 1000,"audio0");
setTimeout(play, 1500,input%10);
}
}
else if(input<20){
var audio = document.getElementById("audio10");
audio.play();
var audio = "audio"+temp;
setTimeout(playaudio, 500,audio);
}
else{
var temp2=Math.floor(input/10);
var audio = "audio"+temp2;
playaudio(audio);
setTimeout(playaudio, 500,"audio10");
if(temp!=0){
var audio = "audio"+temp;
setTimeout(playaudio, 1000,audio);
}
}
}
else{
var audio = document.getElementById("audio"+temp);
audio.play();
}
}
function playaudio(input){
var audio = document.getElementById(input);
audio.play();
setTimeout(audio.pause,480);
}
</script>
(I am a Chinese so my number system is not same as English, it speak like ten-two as twelve and two-ten-two as twenty two)
I expect counting number can be display and play the audio. The numbers can show correctly but the audio usually cannot play after four.
I'm not a professional I do not want to learn using android studio. I just want to use my high school level of HTML and JavaScript to do the task.

How to use vid.onended to detect when a video is done playing using javascript

I am trying to create an HTML video playlist and currently I am using vid.onended to detect when a video is done playing (based of the current video src) and then play the next video when the video ends. This works perfectly for the first video but for some reason it never plays the second video and jumps straight to the third video.
My code:
//add video playlist functionality to auto play next video based on id
var vid = document.getElementById("urlVideo");
vid.onended = function() {
var video0 = "http://techslides.com/demos/sample-videos/small.mp4";
var video1 = "https://media.w3.org/2010/05/sintel/trailer.mp4";
var video2 = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
if (vid.src = video0) {
vid.src = video1;
}
if (vid.src = video1) {
vid.src = video2;
}
};
<video id="urlVideo" width="100%" height="460" controls autoplay>
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
What am I doing wrong?
Edit:
Answer by Alen Toma works perfectly.
I Also managed to do it according to the current video source based on a comment by Quentin, For anyone else looking for how to do it explicitly with the current video source as the variable/condition, please see
https://jsfiddle.net/redlaw/qjb5h7e9/9/
I did make a small example below, it should help.
Have a look at this JSFiddle.
//add video playlist functionality to auto play next video based on id
var videoSrc = [
"https://media.w3.org/2010/05/sintel/trailer.mp4",
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
]
var vid = document.getElementById("urlVideo");
var index = 0;
vid.addEventListener("ended", function() {
var currentSrc = videoSrc[index];
index += 1;
if (index >= videoSrc.length)
index = 0; // Make Loop and jump to the first video
vid.src = currentSrc;
vid.play();
console.log(currentSrc)
}, true);
<video id="urlVideo" controls autoplay>
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
</video>
you must use an event listener for your video player like this code:
var vid = document.getElementById("urlVideo");
vid.addEventListener("ended", function() { /* your code*/ }, true);

Switch video source - same time on slider - JS, HTML5 Video

I have a JS function that changes the video source of an HTML video. A button activates this function. It loads the same new video on switch. There are 2 videos of the same length.
How do I:
interchange the video every time I click the button?
when i click the button, can the video load at the same time the previous video was playing?
HTML:
<button onclick="myFunction()" type="button">Change Video</button><br>
<video id="myVideo" controls autoplay>
<source id="mp4_src" src="video1.mp4" type="video/mp4">
<source id="mp4_src" src="video2.mp4">
</video>
JS
var vid = document.getElementById("myVideo");
function myFunction() {
vid.src = "video2.mp4";
vid.load();
}
Here is the fiddle that solves both of your problems, http://jsfiddle.net/egjyd9rs/5/
Basically, the toggle function which takes care of both is as below,
function myFunction() {
currentlPlayingTime = vid.currentTime;
if (currentlyPlaying === 1) {
vid.src = src2;
currentlyPlaying = 2;
statusElement.innerText = 'Going to play video2..';
} else {
vid.src = src1;
currentlyPlaying = 1;
statusElement.innerText = 'Going to play video1..';
}
vid.load();
vid.addEventListener('loadedmetadata', function () {
vid.currentTime = currentlPlayingTime;
}, false);
}

Play multiple audio files sequentially or randomly in background using HTML5 and javascript

I am trying to play 3 audio files (with the possibility of more later) that run in the background. At this point I am simply trying to play them sequentially and have it loop back to the first audio file when the last is played. I believe I have tried almost every solution or combination of functions and I just can't get it to work. I run into one of two problems:
If I try using repetition with each audio stored in the array, the page will successfully play the first then tries to play the next two simultaneously, rather than sequentially. And it certainly does not go back to the first. Furthermore, if you notice in my html, I have a seperate ID for each player. Would it be better to put them all in the sample player ID?
jQuery(document).ready(function (){
var audioArray = document.getElementsByClassName('playsong');
var i = 0;
var nowPlaying = audioArray[i];
nowPlaying.load();
nowPlaying.play();
while(true){
$('#player').on('ended', function(){
if(i>=2){
i=0;
}
else{
i++;
}
nowPlaying = audioArray[i];
nowPlaying.load();
nowPlaying.play();
});
}
});
On the other hand, I can play each sequentially but each play needs to be hardcoded for and I cannot loop back to the first
jQuery(document).ready(function (){
var audioArray = document.getElementsByClassName('playsong');
var i = 0;
var nowPlaying = audioArray[i];
nowPlaying.load();
nowPlaying.play();
$('#player').on('ended', function(){
// done playing
//alert("Player stopped");
nowPlaying = audioArray[1];
nowPlaying.load();
nowPlaying.play();
$('#player2').on('ended', function(){
nowPlaying = audioArray[2];
nowPlaying.load();
nowPlaying.play();
});
});
});
Here is my html
<audio id="player" class = "playsong">
<source src="1.mp3" />
</audio>
<audio id="player2" class = "playsong">
<source src="2.mp3" />
</audio>
<audio id="player3" class = "playsong">
<source src="3.mp3" />
</audio>
I am not terribly familiar with javascript, I am wondering if there is another event trigger function built into JS that I am not using? Some help is greatly appreciated.
HTML
<audio id="song-1" preload class="songs">
<source src="1.mp3" type="audio/mpeg" />
</audio>
<audio id="song-2" preload class="songs">
<source src="2.mp3" type="audio/mpeg" />
</audio>
<audio id="song-3" preload class="songs">
<source src="3.mp3" type="audio/mpeg" />
</audio>
<audio id="song-4" preload class="songs">
<source src="4.mp3" type="audio/mpeg" />
</audio>
JS
jQuery(document).ready(function (){
var audioArray = document.getElementsByClassName('songs');
var i = 0;
audioArray[i].play();
for (i = 0; i < audioArray.length - 1; ++i) {
audioArray[i].addEventListener('ended', function(e){
var currentSong = e.target;
var next = $(currentSong).nextAll('audio');
if (next.length) $(next[0]).trigger('play');
});
}
});

Audio use js to use image for playpause btn

I am new to js so forgive me. I'm using the html5 audio tag with some js to only show play and pause as a button. I would like to change the text for play & pause out with images. Like playbtn.png and pausebtn.png. Here is where I'm stuck.
html:::
<!-- hidden audio player -->
<audio id="audio" controls autoplay hidden="">
<source src="music/eatForTwo.wav" type="audio/wav">
<source src="music/eatForTwo.mp3" type="audio/mpeg">
<p>Your Browser Doesn't Support The HTML5 audio Element</p>
</audio>
<button id="playpause" title="play" onclick="togglePlayPause()" ><img id="imgbtn" src="music/pausebtn.png"/></button>
<!-- javascript for audio control
-->
<script src="code/html5audio.js" type="text/javascript">
</script>
js:::
// Grab a handle to the video
var audio = document.getElementById("audio");
// Turn off the default controls
audio.controls = false;
function togglePlayPause() {
var playpause = document.getElementById("playpause");
if (audio.paused || audio.ended) {
playpause.title = "pause";
playpause.style.backgroundImage = "url(music\pausebtn.png)";
audio.play();
}
else {
playpause.title = "play";
playpause.style.backgroundImage = "url(music\playbtn.png)";
audio.pause();
}
}
Edit your js as following but you have to change url(c:\folder\img.jpg) to url(yourPath) .... Now yourPath does not mean yourPath it means the location of the image on your hard disk
// Grab a handle to the video
var audio = document.getElementById("audio");
// Turn off the default controls
audio.controls = false;
function togglePlayPause() {
var playpause = document.getElementById("playpause");
if (audio.paused || audio.ended) {
//playpause.title = "pause";
playpause.style.backgroundImage = "url(c:\folder\img.jpg)";
audio.play();
}
else {
//playpause.title = "play";
playpause.style.backgroundImage = "url(c:\img1.jpg)";
audio.pause();
}

Categories