I would like to make 4 play buttons which plays mp3 audio. The play function is working every 4 buttons, but unfortunately the pause is not working for either of them. Maybe the pause condition is wrong?
<div class="audio-button">
<audio src="media/test.mp3"></audio>
</div>
<div class="audio-button">
<audio src="media/test2.mp3"></audio>
</div>
<div class="audio-button">
<audio src="media/test3.mp3"></audio>
</div>
<div class="audio-button">
<audio src="media/test4.mp3"></audio>
</div>
$(document).ready(function() {
var playing = false;
$('.audio-button').click(function() {
$(this).toggleClass("playing");
var song = $(this).find('audio').attr('src');
var audio = new Audio(song);
if (playing == false) {
audio.play();
playing = true;
} else {
audio.pause();
playing = false;
}
});
});
You need to grab the audio element directly from the button as a child and interact with that. You do not need to clone the Audio object using a constructor.
$(document).ready(function() {
var playing = false;
// Add file names.
$('.audio-button').each(function() {
var $button = $(this);
var $audio = $button.find('audio');
$($('<span>').text($audio.attr('src'))).insertBefore($audio);
});
// Add click listener.
$('.audio-button').click(function() {
var $button = $(this);
var audio = $button.find('audio')[0]; // <-- Interact with this!
// Toggle play/pause
if (playing !== true) {
audio.play();
} else {
audio.pause();
}
// Flip state
$button.toggleClass('playing');
playing = !playing
});
});
.fa.audio-button {
position: relative;
display: block;
width: 12em;
height: 2.25em;
margin-bottom: 0.125em;
text-align: left;
}
.fa.audio-button:after {
position: absolute;
right: 0.8em;
content: "\f04b";
}
.fa.audio-button.playing:after {
content: "\f04c";
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="fa audio-button">
<audio src="media/test.mp3"></audio>
</button>
<button class="fa audio-button">
<audio src="media/test2.mp3"></audio>
</button>
<button class="fa audio-button">
<audio src="media/test3.mp3"></audio>
</button>
<button class="fa audio-button">
<audio src="media/test4.mp3"></audio>
</button>
do you want to stop the other three when one is clicked?
If so you can try:
$(document).ready(function () {
$('.audio-button').click(function (e) {
var button = $(e.target).closest('.audio-button');
var audio = button.find('audio');
var audioDom = audio.get(0);
$('audio[data-is-playing]').not(audio).each(function (i, currentAudioDom) {
var currentButton = $(currentAudioDom).closest('.audio-button');
currentButton.removeClass('playing');
currentButton.removeAttr('data-is-playing');
currentAudioDom.$audio.pause();
});
button.addClass('playing');
audio.attr('data-is-playing', '');
audioDom.$audio = audioDom.$audio || new Audio(audio.attr('src'));
audioDom.$audio.play();
});
});
Fix:
Actually I'm not sure if the audio element is an Audio Object in itself, if so, you can call the play/pause directly on the audioDom/currentAudioDom elements and forget about the $audio thing...
Related
I am trying to play an audio which is a smoke detecting sound whenever I sense smoke. But the problem is audio is not playing correctly. If I click the mouse on the page, then sound comes. Even if I press any key from the keyboard, then also sound comes. So, I need a way to play the music without clicking the mouse on the page or pressing any key from the keyboard. Help me out. Thanks.
<tr>
<table align="center" style=" border: 5px solid grey; width:100%;">
<td valign="center"><t style="font-size: 70px; padding-left:0px; color: white; font-family: serif;">SMOKE:</t></td>
<td valign="center">
<i id="smoke" style="font-family: 'verdana'; font-weight: 'bold'; font-size: 75px;">{{ smokestatus }}</i>
</td>
</tr>
<audio id="myAudio">
<source src={{ url_for('static', filename='smoke_detector_beeps.mp3') }} type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<script>
var x = document.getElementById("myAudio");
function playAudio() {
x.play();
}
function pauseAudio() {
x.pause();
}
</script>
<script>
if (document.getElementById('smoke').innerText == "NO SMOKE" ) {
document.getElementById('smoke').style.color = 'green';
}
else if (document.getElementById('smoke').innerText == "SMOKE DETECTED" ) {
document.getElementById('smoke').style.color = 'red';
document.getElementById('smoke').style.fontSize = '65px';
document.getElementById("smoke").className = "blink";
playAudio();
}
else if (document.getElementById('smoke').innerText == "SENSOR DISCONNECTED" ) {
document.getElementById('smoke').style.color = 'yellow';
document.getElementById('smoke').style.fontSize = '60px';
pauseAudio();
}
else if (document.getElementById('smoke').innerText == "SENSOR CONNECTED" ) {
document.getElementById('smoke').style.color = 'green';
}
else {
document.getElementById('smoke').style.color = 'white';
}
</script>
</table>
</tr>
The answer depends on when you want the sound to be played:
If you only want to check for the smoke status on page load, you can wrap your logic that's currently within the second script tag into a function.
This function can then be called when the window loads by using:
window.onload = checkSmoke()
If you want the function to be called multiple times whenever the smoke status changes, you will have to call the function again.
Here's a small JSFiddle to show what I mean.
If this wasn't the answer you were looking for, let me know!
This is a very simple browser memory game which you need to to flip all the matched cards in order to win.
The bug :
In the game if you click fast enough you can flip more than 2 cards.
I've tried a lot to fix it but couldn't figure it out by myself. I would appreciate any help in solving this issue as I am new to JavaScript and it's still hard for me fix those basic bugs.
Game files:
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My App</title>
<link rel="stylesheet" href="css/game.css" />
</head>
<body>
<button class="Change User" onclick="change(this)">Change User</button>
<div class="header">
<img src="img/layout/logo.png">
<h1>Memory Monsters</h1>
<p id="Play Again"></p>
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
<img src="img/cards/1.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="7" onclick="cardClicked(this)">
<img src="img/cards/7.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
<img src="img/cards/1.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="7" onclick="cardClicked(this)">
<img src="img/cards/7.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="5" onclick="cardClicked(this)">
<img src="img/cards/5.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="5" onclick="cardClicked(this)">
<img src="img/cards/5.png">
<img class="back" src="img/cards/back.png">
</div>
<script src="js/game.js"></script>
</body>
</html>
javascript:
var getElementsByClassName = prompt ('What is your name?');
window.localStorage.setItem ('name', 'dan');
function change(username) {
prompt('What is your name?');
}
// Those are global variables, they stay alive and reflect the state of the game
var elPreviousCard = null;
var flippedCouplesCount = 0;
// This is a constant that we dont change during the game (we mark those with CAPITAL letters)
var TOTAL_COUPLES_COUNT = 3;
// Load an audio file
var audioWin = new Audio('sound/win.mp3');
// This function is called whenever the user click a card
function cardClicked(elCard) {
// If the user clicked an already flipped card - do nothing and return from the function
if (elCard.classList.contains('flipped')) {
return;
}
// Flip it
elCard.classList.add('flipped');
// This is a first card, only keep it in the global variable
if (elPreviousCard === null) {
elPreviousCard = elCard;
} else {
// get the data-card attribute's value from both cards
var card1 = elPreviousCard.getAttribute('data-card');
var card2 = elCard.getAttribute('data-card');
// No match, schedule to flip them back in 1 second
if (card1 !== card2){
setTimeout(function () {
elCard.classList.remove('flipped');
elPreviousCard.classList.remove('flipped');
elPreviousCard = null;
}, 1000)
} else {
// Yes! a match!
flippedCouplesCount++;
elPreviousCard = null;
// All cards flipped!
if (TOTAL_COUPLES_COUNT === flippedCouplesCount) {
audioWin.play();
// and finally add a button to call resetCard()
document.getElementById("Play Again").innerHTML =
'<button onclick="resetCard();">Play Again</button>';
}
}
}
}
function resetCard() {// to erase the flipped classes
var cardclass = document.getElementsByClassName("card");
for (i = 0; i < cardclass.length; i++) {
cardclass[i].classList.remove("flipped");
document.getElementById("Play Again").innerHTML = "";
}
}
CSS:
.header {
background-color: lightblue;
padding: 20px;
border-bottom: 10px solid darkcyan;
color:darkcyan;
font-size: 1.5em;
text-align: center;
}
.header img {
float:right;
}
.card {
background-color: pink;
height: 165px;
width: 165px;
float: left;
margin: 5px;
}
.card img {
position: absolute;
}
.flipped .back {
display: none;
}
i made a game like this. you need to create a variable that starts on 0
let tries = 0;
then add one to it each time a card is selected. make sure to not allow it to count if a card that is already flipped is clicked again. here is some of the code from the function that is run on my onclick. I am using a React framework, but if you write this logic in your JS function, it is what you will need to make it work
selected = (event) => {
if (canClick === true) {
let id = event.currentTarget.id; //card0
let idString = id.toString(); //"card0"
//ONLY ALLOW A CARD TO BE CLICKED IF ITS FACE DOWN
if (this.state[idString] === cardBack) {
idString = idString.replace(/card/g, ''); //"0"
this.setState({[id] : arrayRandom[idString]});
//FIRST PICK
if (counter % 2 == 1) {
curCard1 = arrayRandom[idString].toString();
id1 = id;
counter++;
//SECOND PICK
} else {
//MAKE SURE A CARD DOESN'T GET SELECTED TWICE IN A ROW AND STAY FACE UP
if (id === id1) {
console.log("Select a different card for your second pick");
} else {
counter++;
tries++;
canClick = false; //STOP USER FROM SELECTING ANOTHER CARD
curCard2 = arrayRandom[idString].toString();
id2 = id;
setTimeout(() => {canClick = true}, 1000); //USER CAN PICK AGAIN IN 1 SEONCD
//IF THERE'S A MATCH - CARDS STAY FLIPPED, SCORE INCREASES BY 1
if (curCard1 == curCard2) {
score = score + 1;
//IF THERE'S NO MATCH - CARDS FLIP FACE DOWN AFTER A SECOND
} else {
setTimeout(() => {
this.setState({[id1]: cardBack});
this.setState({[id2]: cardBack});
}, 1000);
}
}
}
} else {
console.log("This card has already been flipped, select another one");
}
}
}
here is my game
https://reactcardmatch.netlify.com/
I know the question of closing a pop-up by clicking outside of it has been asked before. I have a somewhat complex pop-up and the solution offered by Phillip Walton isn't working for me.
His code simply made my page blurry but stopped the popup from appearing.
$(document).on('click', function(event) {
if (!$(event.target).closest('.maincontainer').length) {
popup.classList.remove('popup--open');
popup.style.display = 'none';
popupAccessory.style.display = 'none';
popupAccessory.classList.remove('popup--accessory--open');
maincontainer.classList.remove('blurfilter');
}
});
I also tried:
window.addEventListener('click', function(event) {
if (event.target != popup) {
popup.classList.remove('popup--open');
popup.style.display = 'none';
popupAccessory.style.display = 'none';
popupAccessory.classList.remove('popup--accessory--open');
maincontainer.classList.remove('blurfilter');
}
}, true);
This closes the popup when I click anywhere, including on the popup itself. I want it to close only when I click on part of the screen that isn't the popup.
The code to open the popup:
function openpopup() {
popup.style.display = 'initial';
setTimeout(function(){
popup.classList.add('popup--open');
popup.style.boxShadow = '0 0 45px 2px white';
maincontainer.classList.add('blurfilter')}, 10);
for (let i = 0; i < listitems.length; i++ ) {
setTimeout(function() {
listitems[i].classList.add('visible');
}, 100);
}
}
I added the event listener to a button
popupOpenbtn.addEventListener('click', openpopup);
The HTML structure:-
<div class="maincontainer>
...all my page content...
</div>
<div class="popup">
...popup contents...
</div
I would suggest using only css classes to style your popup and use JS only to add, remove and toggle that class. Not sure how close to your working exercise is this fiddle but I've prepared this to show how the document/window click event can be checked to successfully open/close the popup window.
var popupOverlay = document.querySelector('#popup__overlay');
var popupOpenButton = document.querySelector('#popupOpenButton');
var popupCloseButton = document.querySelector('#popupCloseButton');
var mainContainer = document.querySelector('main');
function closestById(el, id) {
while (el.id != id) {
el = el.parentNode;
if (!el) {
return null;
}
}
return el;
}
popupOpenButton.addEventListener('click', function(event) {
popupOverlay.classList.toggle('isVisible');
});
popupCloseButton.addEventListener('click', function(event) {
popupOverlay.classList.toggle('isVisible');
});
mainContainer.addEventListener('click', function(event) {
if (popupOverlay.classList.contains('isVisible') && !closestById(event.target, 'popup__overlay') && event.target !== popupOpenButton) {
popupOverlay.classList.toggle('isVisible');
}
});
#popup__overlay {
display: none;
background-color: rgba(180, 180, 180, 0.5);
position: absolute;
top: 100px;
bottom: 100px;
left: 100px;
right: 100px;
z-index: 9999;
text-align: center;
}
#popup__overlay.isVisible {
display: block;
}
main {
height: 100vh;
}
<aside id="popup__overlay">
<div class="popup">
<h2>Popup title</h2>
<p>
Lorem ipsum
</p>
<button id="popupCloseButton">Close popup</button>
</div>
</aside>
<main>
<div class="buttonWrapper">
<button id="popupOpenButton">Open popup</button>
</div>
</main>
This is a html embed audio player with simple controls . i made this as an addon for my website.
As autoplay is not supported in mobile browsers . The play/pause button changes according to device
ie: Play button shows up in mobile, Pause button shows up on pc's
The mobile side of the player works perfectly. But the pc side of it starts with the play button even though audio is playing in the background. ie. Else condition doesnt work
If the error isnt clear please copy paste the code here and see : www.htmledit.squarefree.com
<head>
<script>
var playing = true;
if (/Android|iPhone|iPad|Mobile|Mobi|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
playing = false;
}
<!-- THIS ELSE DOES NOT WORK . IT IS SUPPOSED TO CHANGE THE ICON TO PAUSE FROM PRE DEFINED PLAY ICON-->
else{
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAuUlEQVRoQ+2YwQ2AIAxFYRwncS3WchLH0YN6IWp/QhtCeJ5rgfd/W0JOg3958P0nDtBbQRRAgUYCWKgRYPPv8yiwlO1QcO1l/YXilefZi6yA18JeeTjAl52w0E3GAoGFsJDRk7FQDcirf3vloYgpYor4IsBlrnaC1b/pQhUxLISFPtqpVUtMYiYxk5hJ/O4Bq3swiaedxMq7aI8Y+S7UY3PKmhxAoRQZgwKRdJXcKKBQioxBgUi6Su4TGV3gMZ8LoyUAAAAASUVORK5CYII=";
}
function EvalSound(soundobj) {
var thissound = document.getElementById(soundobj);
if (!playing) {
thissound.play();
playing = true;
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAuUlEQVRoQ+2YwQ2AIAxFYRwncS3WchLH0YN6IWp/QhtCeJ5rgfd/W0JOg3958P0nDtBbQRRAgUYCWKgRYPPv8yiwlO1QcO1l/YXilefZi6yA18JeeTjAl52w0E3GAoGFsJDRk7FQDcirf3vloYgpYor4IsBlrnaC1b/pQhUxLISFPtqpVUtMYiYxk5hJ/O4Bq3swiaedxMq7aI8Y+S7UY3PKmhxAoRQZgwKRdJXcKKBQioxBgUi6Su4TGV3gMZ8LoyUAAAAASUVORK5CYII=";
} else if (playing) {
thissound.pause();
playing = false;
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABdElEQVRoQ+2YuxWCQBBFl0Rb0TJM9NiFdoAVOHSAHWAZZtoFoXagGZHroOghMHA+++G4JCT7mTvv8VjIzMCvbOD1mwQQWsGkQFJA2IFkIWEDxdP/V4EJHI7G3Fc1LM/iNgoWYCswhYNt97WZgcaOdmeYXQV1sKeKAbqdrwiS19vFnl0Jc6IWwHN7ayzayhZoK7z7uVQB3iUjSNWY8caHrZwA9GxVoq0Kl1q4BHjbClPKrl3ZyjlAz1bt89GCqMauN4APiHLsegfQjt1QAGqxGxRAI3ajAJDEbkwArNiNDgCj9oJv8vaU+9NxJBoAPNreUIKyhgVQ3txRAGDx+8aMcs7ZKSgAFn7CjyL41S7flAkC8LJLltcwryh2iQIAiy/QLiXHLkEBOruof0N7sBAtFqmWcgbAjcUoACSxGBRAIxaDAGjGoncA7Vj0BjD4X4vUTrkaz45RVwVR100A1I5pj08KaHeUul5SgNox7fFJAe2OUtd7AO2p3zFrWh4hAAAAAElFTkSuQmCC";
}
}
</script>
</head>
<body>
<a href="javascript:null()" onClick="EvalSound('sound1'); return false; ">
<!-- PRE DEFINED PLAY ICON IS BELOW -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABdElEQVRoQ+2YuxWCQBBFl0Rb0TJM9NiFdoAVOHSAHWAZZtoFoXagGZHroOghMHA+++G4JCT7mTvv8VjIzMCvbOD1mwQQWsGkQFJA2IFkIWEDxdP/V4EJHI7G3Fc1LM/iNgoWYCswhYNt97WZgcaOdmeYXQV1sKeKAbqdrwiS19vFnl0Jc6IWwHN7ayzayhZoK7z7uVQB3iUjSNWY8caHrZwA9GxVoq0Kl1q4BHjbClPKrl3ZyjlAz1bt89GCqMauN4APiHLsegfQjt1QAGqxGxRAI3ajAJDEbkwArNiNDgCj9oJv8vaU+9NxJBoAPNreUIKyhgVQ3txRAGDx+8aMcs7ZKSgAFn7CjyL41S7flAkC8LJLltcwryh2iQIAiy/QLiXHLkEBOruof0N7sBAtFqmWcgbAjcUoACSxGBRAIxaDAGjGoncA7Vj0BjD4X4vUTrkaz45RVwVR100A1I5pj08KaHeUul5SgNox7fFJAe2OUtd7AO2p3zFrWh4hAAAAAElFTkSuQmCC" id="sound_icon" name="Sound" width="" height="" title="Background Music Controls" class="" /></a>
<audio id="sound1" style="display: none; width: 0px; height: 0px;" src="https://audio.clyp.it/3fnnuaiw.mp3?Expires=1488659248&Signature=01NkRScwYO4XaJO46JuNzPRR6cYQfcL5~rJzAu-gIoNoXkiMVZwazwT--amuqYvreLCSRFnFAFUvwR3v9Xaq1iB4~OmKSWqtF9mSm-CUB2Moqtie8wpGIRxTAkDHnfhN0sy45sINjwFP2xyVumld78USPuCBfNU3kgux69YG-yA_&Key-Pair-Id=APKAJ4AMQB3XYIRCZ5PA" controls preload="auto" autobuffer autoplay>
</body>
When loading the page the script part at the headers is running before the elements where created at the DOM. See this other answer to better understand how it works.
To have it working you can load the script at the end:
<body>
<a href="javascript:null()" onClick="EvalSound('sound1'); return false; ">
<!-- PRE DEFINED PLAY ICON IS BELOW -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABdElEQVRoQ+2YuxWCQBBFl0Rb0TJM9NiFdoAVOHSAHWAZZtoFoXagGZHroOghMHA+++G4JCT7mTvv8VjIzMCvbOD1mwQQWsGkQFJA2IFkIWEDxdP/V4EJHI7G3Fc1LM/iNgoWYCswhYNt97WZgcaOdmeYXQV1sKeKAbqdrwiS19vFnl0Jc6IWwHN7ayzayhZoK7z7uVQB3iUjSNWY8caHrZwA9GxVoq0Kl1q4BHjbClPKrl3ZyjlAz1bt89GCqMauN4APiHLsegfQjt1QAGqxGxRAI3ajAJDEbkwArNiNDgCj9oJv8vaU+9NxJBoAPNreUIKyhgVQ3txRAGDx+8aMcs7ZKSgAFn7CjyL41S7flAkC8LJLltcwryh2iQIAiy/QLiXHLkEBOruof0N7sBAtFqmWcgbAjcUoACSxGBRAIxaDAGjGoncA7Vj0BjD4X4vUTrkaz45RVwVR100A1I5pj08KaHeUul5SgNox7fFJAe2OUtd7AO2p3zFrWh4hAAAAAElFTkSuQmCC" id="sound_icon" name="Sound" width="" height="" title="Background Music Controls" class="" /></a>
<audio id="sound1" style="display: none; width: 0px; height: 0px;" src="https://audio.clyp.it/3fnnuaiw.mp3?Expires=1488659248&Signature=01NkRScwYO4XaJO46JuNzPRR6cYQfcL5~rJzAu-gIoNoXkiMVZwazwT--amuqYvreLCSRFnFAFUvwR3v9Xaq1iB4~OmKSWqtF9mSm-CUB2Moqtie8wpGIRxTAkDHnfhN0sy45sINjwFP2xyVumld78USPuCBfNU3kgux69YG-yA_&Key-Pair-Id=APKAJ4AMQB3XYIRCZ5PA" controls preload="auto" autobuffer autoplay>
<script>
var playing = true;
var flag = false;
if (/Android|iPhone|iPad|Mobile|Mobi|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
playing = false;
} else{
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAuUlEQVRoQ+2YwQ2AIAxFYRwncS3WchLH0YN6IWp/QhtCeJ5rgfd/W0JOg3958P0nDtBbQRRAgUYCWKgRYPPv8yiwlO1QcO1l/YXilefZi6yA18JeeTjAl52w0E3GAoGFsJDRk7FQDcirf3vloYgpYor4IsBlrnaC1b/pQhUxLISFPtqpVUtMYiYxk5hJ/O4Bq3swiaedxMq7aI8Y+S7UY3PKmhxAoRQZgwKRdJXcKKBQioxBgUi6Su4TGV3gMZ8LoyUAAAAASUVORK5CYII=";
}
function EvalSound(soundobj) {
var thissound = document.getElementById(soundobj);
if (!playing) {
thissound.play();
playing = true;
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAuUlEQVRoQ+2YwQ2AIAxFYRwncS3WchLH0YN6IWp/QhtCeJ5rgfd/W0JOg3958P0nDtBbQRRAgUYCWKgRYPPv8yiwlO1QcO1l/YXilefZi6yA18JeeTjAl52w0E3GAoGFsJDRk7FQDcirf3vloYgpYor4IsBlrnaC1b/pQhUxLISFPtqpVUtMYiYxk5hJ/O4Bq3swiaedxMq7aI8Y+S7UY3PKmhxAoRQZgwKRdJXcKKBQioxBgUi6Su4TGV3gMZ8LoyUAAAAASUVORK5CYII=";
} else if (playing) {
thissound.pause();
playing = false;
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABdElEQVRoQ+2YuxWCQBBFl0Rb0TJM9NiFdoAVOHSAHWAZZtoFoXagGZHroOghMHA+++G4JCT7mTvv8VjIzMCvbOD1mwQQWsGkQFJA2IFkIWEDxdP/V4EJHI7G3Fc1LM/iNgoWYCswhYNt97WZgcaOdmeYXQV1sKeKAbqdrwiS19vFnl0Jc6IWwHN7ayzayhZoK7z7uVQB3iUjSNWY8caHrZwA9GxVoq0Kl1q4BHjbClPKrl3ZyjlAz1bt89GCqMauN4APiHLsegfQjt1QAGqxGxRAI3ajAJDEbkwArNiNDgCj9oJv8vaU+9NxJBoAPNreUIKyhgVQ3txRAGDx+8aMcs7ZKSgAFn7CjyL41S7flAkC8LJLltcwryh2iQIAiy/QLiXHLkEBOruof0N7sBAtFqmWcgbAjcUoACSxGBRAIxaDAGjGoncA7Vj0BjD4X4vUTrkaz45RVwVR100A1I5pj08KaHeUul5SgNox7fFJAe2OUtd7AO2p3zFrWh4hAAAAAElFTkSuQmCC";
}
}
</script>
</body>
or load after window is loaded with window.onload
<head>
<script>
var playing = true;
var flag = false;
window.onload = function () {
if (/Android|iPhone|iPad|Mobile|Mobi|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
playing = false;
} else {
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAuUlEQVRoQ+2YwQ2AIAxFYRwncS3WchLH0YN6IWp/QhtCeJ5rgfd/W0JOg3958P0nDtBbQRRAgUYCWKgRYPPv8yiwlO1QcO1l/YXilefZi6yA18JeeTjAl52w0E3GAoGFsJDRk7FQDcirf3vloYgpYor4IsBlrnaC1b/pQhUxLISFPtqpVUtMYiYxk5hJ/O4Bq3swiaedxMq7aI8Y+S7UY3PKmhxAoRQZgwKRdJXcKKBQioxBgUi6Su4TGV3gMZ8LoyUAAAAASUVORK5CYII=";
}
}
function EvalSound(soundobj) {
var thissound = document.getElementById(soundobj);
if (!playing) {
thissound.play();
playing = true;
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAuUlEQVRoQ+2YwQ2AIAxFYRwncS3WchLH0YN6IWp/QhtCeJ5rgfd/W0JOg3958P0nDtBbQRRAgUYCWKgRYPPv8yiwlO1QcO1l/YXilefZi6yA18JeeTjAl52w0E3GAoGFsJDRk7FQDcirf3vloYgpYor4IsBlrnaC1b/pQhUxLISFPtqpVUtMYiYxk5hJ/O4Bq3swiaedxMq7aI8Y+S7UY3PKmhxAoRQZgwKRdJXcKKBQioxBgUi6Su4TGV3gMZ8LoyUAAAAASUVORK5CYII=";
} else if (playing) {
thissound.pause();
playing = false;
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABdElEQVRoQ+2YuxWCQBBFl0Rb0TJM9NiFdoAVOHSAHWAZZtoFoXagGZHroOghMHA+++G4JCT7mTvv8VjIzMCvbOD1mwQQWsGkQFJA2IFkIWEDxdP/V4EJHI7G3Fc1LM/iNgoWYCswhYNt97WZgcaOdmeYXQV1sKeKAbqdrwiS19vFnl0Jc6IWwHN7ayzayhZoK7z7uVQB3iUjSNWY8caHrZwA9GxVoq0Kl1q4BHjbClPKrl3ZyjlAz1bt89GCqMauN4APiHLsegfQjt1QAGqxGxRAI3ajAJDEbkwArNiNDgCj9oJv8vaU+9NxJBoAPNreUIKyhgVQ3txRAGDx+8aMcs7ZKSgAFn7CjyL41S7flAkC8LJLltcwryh2iQIAiy/QLiXHLkEBOruof0N7sBAtFqmWcgbAjcUoACSxGBRAIxaDAGjGoncA7Vj0BjD4X4vUTrkaz45RVwVR100A1I5pj08KaHeUul5SgNox7fFJAe2OUtd7AO2p3zFrWh4hAAAAAElFTkSuQmCC";
}
}
</script>
</head>
<body>
<a href="javascript:null()" onClick="EvalSound('sound1'); return false; ">
<!-- PRE DEFINED PLAY ICON IS BELOW -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABdElEQVRoQ+2YuxWCQBBFl0Rb0TJM9NiFdoAVOHSAHWAZZtoFoXagGZHroOghMHA+++G4JCT7mTvv8VjIzMCvbOD1mwQQWsGkQFJA2IFkIWEDxdP/V4EJHI7G3Fc1LM/iNgoWYCswhYNt97WZgcaOdmeYXQV1sKeKAbqdrwiS19vFnl0Jc6IWwHN7ayzayhZoK7z7uVQB3iUjSNWY8caHrZwA9GxVoq0Kl1q4BHjbClPKrl3ZyjlAz1bt89GCqMauN4APiHLsegfQjt1QAGqxGxRAI3ajAJDEbkwArNiNDgCj9oJv8vaU+9NxJBoAPNreUIKyhgVQ3txRAGDx+8aMcs7ZKSgAFn7CjyL41S7flAkC8LJLltcwryh2iQIAiy/QLiXHLkEBOruof0N7sBAtFqmWcgbAjcUoACSxGBRAIxaDAGjGoncA7Vj0BjD4X4vUTrkaz45RVwVR100A1I5pj08KaHeUul5SgNox7fFJAe2OUtd7AO2p3zFrWh4hAAAAAElFTkSuQmCC" id="sound_icon" name="Sound" width="" height="" title="Background Music Controls" class="" /></a>
<audio id="sound1" style="display: none; width: 0px; height: 0px;" src="https://audio.clyp.it/3fnnuaiw.mp3?Expires=1488659248&Signature=01NkRScwYO4XaJO46JuNzPRR6cYQfcL5~rJzAu-gIoNoXkiMVZwazwT--amuqYvreLCSRFnFAFUvwR3v9Xaq1iB4~OmKSWqtF9mSm-CUB2Moqtie8wpGIRxTAkDHnfhN0sy45sINjwFP2xyVumld78USPuCBfNU3kgux69YG-yA_&Key-Pair-Id=APKAJ4AMQB3XYIRCZ5PA" controls preload="auto" autobuffer autoplay>
</body>
I am trying to start and stop a sound, when a button, which class changes with .toggleClass() is clicked. The sound should start when i click the button and stop when i click it again or when another button, which plays another sound is clicked. But instead of stopping, the sound just starts playing from the beginning when i click the button again. I tried several methods but nothing seems to work with the current code i have. It is important for me, that the sound is also stopped, when another sound is being played. That works already.
I hope you are able to understand what i mean, I don't know how to explain it better. (Sorry for my bad english and just hit me up if you have any questions). I would be glad if someone could help me.
That is my attempt at stopping the sound:
$(document).ready(function () {
$(".fa-volume-up").click(function () {
$('audio').each(function () {
this.pause();
this.currentTime = 0;
});
});
});
And here is my whole code:
//Icon color change
$(document).ready(function() {
$(".fa-volume-off,.fa-volume-up").click(function() {
$(".fa-volume-off").toggleClass("fa-volume-up");
});
});
//Sound
var currentsound;
function EvalSound(soundobj) {
if (currentsound) {
currentsound.pause();
}
var thissound = document.getElementById(soundobj);
thissound.currentTime = 0;
thissound.play();
currentsound = thissound;
}
//Stop sound on click
$(document).ready(function() {
$(".fa-volume-up").click(function() {
$('audio').each(function() {
this.pause();
this.currentTime = 0;
});
});
});
/*basic document style*/
body,
html {
font-family: 'Open Sans', sans-serif;
font-size: 18px;
}
p {
width: 400px;
margin: auto;
margin-top: 50px;
}
audio {
display: none;
}
/*Icon style*/
.fa-volume-off {
width: 14px;
}
.fa-volume-up {
color: #3ad27a;
}
.fa-volume-off,
.fa-volume-up:hover {
cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="http://fortawesome.github.io/Font-Awesome/assets/font-awesome/css/font-awesome.css">
<p>
A wonderful serenity has taken possession of my entire soul, whole heart. Israel (Sparring) - Chance The Rapper
<i class="fa fa-volume-off" onClick="EvalSound('sound1');StopSound(soundobj)"></i>
I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine.
</p>
<audio class="audio" id="sound1" src="http://soundbible.com//mp3/Coin_Drop-Willem_Hunt-569197907.mp3" controls preload="auto" autobuffer></audio>
I just figured out how to do this without adding new classes and ids for every sound element.
Here is the working js code:
$(document).ready(function () {
//change icon and icon color
$(".fa-volume-off,.fa-volume-up").click(function () {
$(this).toggleClass("fa-volume-up");
$('.fa-volume-up').not($(this)).removeClass('fa-volume-up');
//stop audio on second button click
$(".speaker").click(function () {
if (!$(this).hasClass("fa-volume-up")) {
$(".audio").trigger("pause");
}
});
});});
//stop sound and start different sound
var currentsound;
function EvalSound(soundobj) {
if (currentsound) {
currentsound.pause();
}
var thissound = document.getElementById(soundobj);
thissound.currentTime = 0;
thissound.play();
currentsound = thissound;
};
And the demo:
$(document).ready(function() {
//change icon and icon color
$(".fa-volume-off,.fa-volume-up").click(function() {
$(this).toggleClass("fa-volume-up");
$('.fa-volume-up').not($(this)).removeClass('fa-volume-up');
//stop audio on second button click
$(".speaker").click(function() {
if (!$(this).hasClass("fa-volume-up")) {
$(".audio").trigger("pause");
}
});
});
});
//stop sound and start second sound
var currentsound;
function EvalSound(soundobj) {
if (currentsound) {
currentsound.pause();
}
var thissound = document.getElementById(soundobj);
thissound.currentTime = 0;
thissound.play();
currentsound = thissound;
};
/*basic document style*/
body,
html {
font-family: 'Open Sans', sans-serif;
font-size: 18px;
font-weight: 400;
}
p {
width: 400px;
margin: auto;
margin-top: 50px;
}
audio {
display: none;
}
/*Icon style*/
.fa-volume-off {
width: 14px;
}
.fa-volume-up {
color: #3ad27a;
}
.fa-volume-off,
.fa-volume-up:hover {
cursor: pointer
}
<link href="https://fontawesome.io/assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'>
<p>
A wonderful serenity has taken possession of my entire soul, whole heart. Israel (Sparring) - Chance The Rapper
<i class="fa fa-volume-off speaker" onClick="EvalSound('sound1');StopSound(soundobj)"></i> I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine.
<i class="fa fa-volume-off speaker" onClick="EvalSound('sound2');StopSound(soundobj);SoundEnded();"></i> A wonderful serenity has taken possession of my entire soul, whole heart.<i class="fa fa-volume-off speaker" onClick="EvalSound('sound3');StopSound(soundobj)"></i>
</p>
<audio class="audio" id="sound1" src="http://soundbible.com//mp3/Coin_Drop-Willem_Hunt-569197907.mp3" controls preload="auto" autobuffer></audio>
<audio class="audio" id="sound2" src="wiz.mp3" controls preload="auto" autobuffer></audio>
<audio class="audio" id="sound3" src="drake.m4a" controls preload="auto" autobuffer></audio>
Here is the code
$(document).ready(function () {
$(".audio-control").click(function () {
var audio = $('.audio').get(0);
if (audio.paused == false) {
$('.audio-control').removeClass('fa-volume-up').addClass('fa-volume-off');
audio.pause();
} else {
$('.audio-control').removeClass('fa-volume-off').addClass('fa-volume-up');
audio.play();
}
});
});
and here is the example
https://jsfiddle.net/5f2cbs0m/2/