Play an audio file repeatedly with fast button clicks - javascript

I'm tring to provide audio feed back on a button using html5 audio.
It works fine when clicking slowly, but when clicking the button faster it misses some of the clicks.
http://jsfiddle.net/sWsTb/
HTML
<div id="count">0</div>
<button>Click</button>
JS
var snd = new Audio("https://dl.dropbox.com/u/14037764/Development/jsfiddle/click2.mp3");
var count = 0;
$("button").click(function () {
snd.pause();
snd.currentTime = 0;
snd.play();
count++;
$("#count").text(count);
return false;
});
After adding snd.pause(); and snd.currentTime = 0; lines, it's better but still misses some of the fast clicks. Is there any way to fix that?

Related

Play random sound on button that is spammable

I have a problem that i want to have a button, that plays random sound after I press it, but the other thing is that i want to spam the button and so does the sound. What I mean is that i dont want to wait for the sound to finish to play it again and like have 5 sounds or more playing depending on your click speed.
for(var i=0;i<1;i++)
{
document.getElementById("MyAudio.mp3")[i].addEventListener("click",function(){});
}
function playAudio()
{
var audio = new Audio("MyAudio.mp3");
audio.play();
}
<button onlick="playAudio()"></button>
That sounds fun and there's many ways to do it. I think the easiest way would be to pre-load the songs ahead of time and randomize it.
// Your sounds
let sounds = [new Audio('https://download.samplelib.com/mp3/sample-3s.mp3'), new Audio('https://download.samplelib.com/mp3/sample-6s.mp3'), new Audio('https://www.soundjay.com/human/fart-01.mp3')];
let lastSound = 0; // Not necessary but we don't want overlapping tracks.
// Listen for click on button (ID soundmachine)
// pointerdown is more suitable so adjusted it.
document.querySelector("#soundmachine1").addEventListener("pointerdown", () => {
// This is a small fix to allow the sound to be spammable and clear last track.
sounds[lastSound].pause();
sounds[lastSound].currentTime = 0;
let random = Math.floor(Math.random() * sounds.length);
sounds[random].play();
lastSound = random; // For the next click we want to cancel this sound if it's playing.
console.log(lastSound); // Just so you can see it count/play
});
document.querySelector("#soundmachine2").addEventListener("pointerdown", () => {
// Play till completed
let random = Math.floor(Math.random() * sounds.length);
sounds[random].play();
});
<button id="soundmachine1">click me ver1</div>
<button id="soundmachine2">click me ver2</div>
Something like this!
There's some odd things going on with this code, so let's rethink it from the beginning. First of all, you want to create an onclick handler on your button that plays your mp3 file. Let's do that first:
let audio = new Audio("MyAudio.mp3");
document.querySelector("button").addEventListener("click", () => {
audio.play()
});
Now, it sounds like you want it to play from the beginning every time when clicked, and not wait till it completes (which is the default behavior). So we need to reset the playback every time you click.
let audio = new Audio("MyAudio.mp3");
document.querySelector("button").addEventListener("click", () => {
audio.currentTime = 0;
audio.play();
});
🎉 🎶
And your HTML can just look like this:
<button>Play</button>

How can I play different sound files on click?

I built a simple matching game and added audio files for several cards like this:
cardList.map((cardItem) => {
var card = document.createElement("li");
card.classList.add("card");
var img = document.createElement("img");
img.src = [cardItem.img]
card.appendChild(img);
//audio starting here
audio = new Audio(cardItem.sound);
card.appendChild(audio);
audio.id += ' ' + cardItem.card;
deck.append(card);
card.className += ' ' + cardItem.name;
});
}
And in my startGame() function I added an eventListener to add audio.play(); on click.
So now, when I open dev tools, I can see audio elements for my cards but when I try and click on them, I'm only ever getting one audio file for all cards and not the audios I actually added to that specific element.
That's my GitHub file: https://github.com/cMikolai/guitar-colour-system-game/blob/master/js/app.js
Could anybody try and help me figure out how I could play the sound I added to the card I am clicking on?
I downloaded your code and played around. The code for playing audio is in the function startGame() in your app.js file.
app.js:
audio = []; // local variable declaration
...
...
// some code
function startGame() {
// some code
for (var i = 0; i < clickedCard.length; i++) {
clickedCard[i].addEventListener("click", function( event ) {
this.classList.add("open", "show");
openCards.push(this.getAttribute("class"));
audio.load();
audio.play(); // this is the line playing the audio
matchCards();
starRating();
}, false);
}
}
As you can see, you are not playing audio from the selected card but from the local variable audio.
So, you have to identify the selected card and play its respective audio instead of playing audio from the local variable.

Running a javascript animation followed by redirecting

So I'm fiddling with a fun idea for an offline website I'm currently trying to develop.
It'll be offline as it's meant to be practice for later study assignments and such.
My problem is the following: I have a javascript function that replaces a PNG with a GIF and after the animation it should redirect the person to another html I've made.
The source for the JS animation is mainly acquired from here already, but I cannot seem to make it work in the ways I originally intended.
The way it currently works is that I click the png and it'll turn into a gif (no problem there) but what I want is that it runs my js script and then redirect to another .html file (url).
The following is my HTML:
<object id="syringe">
<img src="img/syringe.png" height="750" alt="img/syringe.gif" class="center">
<h2>Click the syringe to inject yourself with a daily dose of puns and jokes</h2>
</object>
The following is the JS:
(function($) {
var getGif = function() {
var gif = [];
$('img').each(function() {
var data = $(this).data('alt');
gif.push(data);
});
return gif;
}
var gif = getGif();
var image = [];
$.each(gif, function(index) {
image[index] = new Image();
image[index].src = gif[index];
});
$('#syringe').on('click', function() {
var $this = $(this),
$index = $this.index(),
$img = $this.children('img'),
$imgSrc = $img.attr('src'),
$imgAlt = $img.attr('data-alt'),
$imgExt = $imgAlt.split('.');
if($imgExt[1] === 'gif') {
$img.attr('src', $img.data('alt')).attr('data-alt', $imgSrc);
} else {
$img.attr('src', $imgAlt).attr('data-alt', $img.data('alt'));
}
$this.toggleClass('play');
});
})(jQuery);
It is to my understanding that I can add a delay and then another function to something in the js - such as the following, which is what I intend to do, however cannot accomplish.
[FUNCTION HERE],1000,
function(){
window.location.href=myredirectionuri;
});
And that is my problem.
It looks like you want to have the gif display for a second or two and then redirect, right? If $this.toggleClass('play'); is the end, then just insert this right after it:
setTimeout(() => window.location.href = myredirectionuri, 1000);
That'll wait for 1000ms and then redirect to the new page.
In the animation script, after it changes to a gif, insert
setTimeout(function() {
/* redirect code */
}, /* length of gif in milliseconds */ )

restarting canvas slot game

i made a slot machine game with 3 buttons, play, stop, refresh.. the play button starts the spinning, the stop button stops the spin on selected images, i just need to add a refresh button to refresh the game, restart like it the window was just opened.
<div id="buttons">
<div id="play" class="butn butn--stripe">spin</div>
<div id="setStopAt" class="butn butn--stripe">stop</div>
<div id="refresh" class="butn butn--stripe">refresh</div>
</div>
the html declaration of the buttons
Game.prototype.restart = function() {
this.lastUpdate = new Date();
this.speed1 = this.speed2 = this.speed3 = SLOT_SPEED
// function locates id from items
function _find(items, id) {
for (var i = 0; i < items.length; i++) {
if (items[i].id == id)
return i;
}
}
// Clear stop locations
this.stopped1 = false;
this.stopped2 = false;
this.stopped3 = false;
// randomize reel locations
this.offset1 = -parseInt(Math.random(ITEM_COUNT)) * SLOT_HEIGHT;
this.offset2 = -parseInt(Math.random(ITEM_COUNT)) * SLOT_HEIGHT;
this.offset3 = -parseInt(Math.random(ITEM_COUNT)) * SLOT_HEIGHT;
$('#results').hide();
game.increaseSpeed();
this.state = 2;
}
If you are alright with a complete restart then binding Program.restart(); to your restart button might be your best bet. Otherwise this may help;
https://css-tricks.com/forums/topic/organize-js-game-restart-button/

Javascript Sound Start/Stop and Image Change

I am new to JS and I have a pretty simple-seeming problem.
I want to have a small image that when clicked changes to a different image and at the same time begins playing a looped sound file. When the image is clicked a second time it changes back to the original image and also stops the sound file.
You can think of it as a button that says "start". when "start" is clicked it loops the sound and changes to "stop" and when "stop" is clicked it goes back to start and the sound ceases playing.
I've gotten as far as creating none-displayed checkbox inside of a label which is a square that when checked plays sound and when unchecked stops sound. Problem is I can't get the checkbox to change into different images with "check", "uncheck".
I've also got some code that has a link change images, but I cannot figure out how to make it play the sound.
SO basically i need to combine these two things. BUT I CAN'T figure out how. And I've been googling for the past two days nonstop but cannot find a clearcut and simple answer.
It may help to know that I plan on having many of these small clickable images on the same page, so the Javascript needs to be able to be light but effect all of the links or divs or whatever they are in the end.
Sorry for such a long question. Anybody?
Thanks in advance!
<html>
<head>
<script type="text/javascript">
var pos = 0
var sId = 'sound';
function change() {
if(pos == 0) {
pos = 1;
document.getElementById('btn').src="http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png";
var e = document.createElement('embed');
e.setAttribute('src','beep.mp3');
e.setAttribute('id',sId);
e.setAttribute('hidden','true');
e.setAttribute('autostart','true');
e.setAttribute('loop','true');
document.body.appendChild(e);
} else {
pos = 0;
document.getElementById('btn').src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png";
document.body.removeChild(document.getElementById(sId));
}
}
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="change()" id="btn" />
</body>
</html>
How about that, I think it should work.
Edit:
Here is an OO version that should do what you need:
<html>
<head>
<script type="text/javascript">
function imageSwitch(_imgID,_imgStart,_imgStop,_soundFile) {
this.imgID = _imgID;
this.imgStart = _imgStart;
this.imgStop = _imgStop;
this.soundFile = _soundFile;
this.pos = 0;
this.e;
this.change = function() {
if(this.pos == 0) {
this.pos = 1;
document.getElementById(this.imgID).src = this.imgStop;
this.e = document.createElement('embed');
this.e.setAttribute('src',this.soundFile);
this.e.setAttribute('id','sound'+this.imgID);
this.e.setAttribute('hidden','true');
this.e.setAttribute('autostart','true');
this.e.setAttribute('loop','true');
document.body.appendChild(this.e);
} else {
this.pos = 0;
document.getElementById(this.imgID).src = this.imgStart;
this.e.parentNode.removeChild(this.e);
}
}
}
</script>
<script type="text/javascript">
var abc = new imageSwitch('btn1','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
var def = new imageSwitch('btn2','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="abc.change()" id="btn1" />
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="def.change()" id="btn2" />
</body>
</html>

Categories

Resources