How to toggle audio play() pause() with one button or link? - javascript

I have an audio file that plays when an anchor tag is clicked. If the anchor tag is clicked again, I want the audio to pause, I just don't know enough about javascript to pull this second half off. I don't want to change the content of the anchor tag they click, I just want the audio file to start and pause whenever they click the tag.
This is what I have so far, which at least makes the sound file playable:
<audio id="audio" src="/Demo.mp3"></audio>
<a onClick="document.getElementById('audio').play()">Click here to hear.</a>

A Vanilla Javascript way to do what you required.
Note: I've noticed comments on other question with multiple upvotes for a native js approach and saw the OP has no jquery tag.
So WORKING EXAMPLE:
SOLN 1: (my initial soln using events)
var myAudio = document.getElementById("myAudio");
var isPlaying = false;
function togglePlay() {
isPlaying ? myAudio.pause() : myAudio.play();
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
<audio id="myAudio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
<a onClick="togglePlay()">Click here to hear.</a>
SOLN 2: (using myAudio.paused property based on dandavi's comment)
var myAudio = document.getElementById("myAudio");
function togglePlay() {
return myAudio.paused ? myAudio.play() : myAudio.pause();
};
<audio id="myAudio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
<a onClick="togglePlay()">Click here to hear.</a>

var audioElement= document.getElementById("audio-player");
function togglePlay() {
if (audioElement.paused) {
audioElement.play();
}
else {
audioElement.pause();
}
};

You could use jQuery to make a toggle for this.
<a id="music-button" style="cursor:pointer;">
<img src="http://i.stack.imgur.com/LT3WE.png"></a>
<audio id="playMusic" autoplay>
<source src="sound.mp3">
</audio>
<script type="text/javascript">
$('#music-button').toggle(
function () {
document.getElementById('playMusic').play();
},
function () {
document.getElementById('playMusic').pause();
}
);
</script>

the myAudio variable has to be inside the function call...It works fine
function togglePlay() {
var myAudio = document.getElementById("myAudio");
return myAudio.paused ? myAudio.play() : myAudio.pause();
};
<audio
id="myAudio" src="https://clubajax.pythonanywhere.com/media/contact/backgroundM.mp3" preload="auto">
</audio>
<input type="button" value="sound" onclick="togglePlay()" />

var Sample-Audio = document.getElementById("Sample");
function togglePlay() {
return Sample-Audio.paused ? Sample-Audio.play() : Sample-Audio.pause();
};
<audio id="Sample" preload="auto">
<source src="./sounds/rain.mp4" type="audio/mp4">
<source src="./sounds/rain.ogg" type="video/ogg">
</audio>
<a onClick="togglePlay()">Click here to hear.</a>

HTML
<audio controls autoplay class="bgsound">
<source src="audio/motivational-day-112790.mp3" type="audio/wav" />
<source src="audio/motivational-day-112790.mp3" type="audio/wav" />
<source src="audio/motivational-day-112790.mp3" type="audio/wav" />
Your browser does not support the audio element.
</audio>
Javascript
var audioClass = document.querySelector(".bgsound");
document.querySelector(".play-pause").addEventListener("click",
function () {
if (audioClass.paused) {
audioClass.play();
} else {
audioClass.pause();
}
});

Related

Save a css display value in Local Storage

I have a page with some videos showing like a web course: so after the first one finishes, the second one appears and so on.
The code used is very simple, with a display none/block function.
**What I want to do is to save in localStorage when a video changes from display "none" to "block", and retrieve it on Page Load** (because I don't want to start again from video 1 every time I load or refresh the page).
Some conditions:
I must use a specific internal platform, very old, to load my code. Is customized by the place where I work
I can't use external libraries or tag too new
I search for the simpliest, pure solution code
the code down is a part of the one I used, I assure this is the only working way, I tried better ways but nothing
Here the code with 2 videos:
html
<script type="text/javascript">
document.getElementById('Video1').addEventListener('ended',myHandler,false);
function myHandler(e) {
var video2 = document.getElementById("Video2");
if ( video2.style.display === "none") {
video2.style.display = "block";
} else {
}
}
</script>
<video id="Video1" controls="" width="320" height="240">
<source src="https://www.tdblog.it/wp-content/uploads/2020/07/Video_aruba_200721_04.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<video id="Video2" controls="" style="display:none; float:right;" width="320" height="240">
<source src="https://www.tdblog.it/wp-content/uploads/2020/06/1160438711001_6017851885001_6017852130001.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
Thanks for the help!
Here the new code:
<script type="text/javascript">
document.getElementById('Video1').addEventListener('ended',myHandler,false);
function myHandler(e) {
var video2 = document.getElementById("Video2");
if ( video2.style.display === "none") {
video2.style.display = "block";
localStorage.setItem('video1Completed', 'true');
} else {
}
}
window.onload = function(){
localStorage.getItem('video1Completed')=='true' {
Video2.style.display = "block";
} else {
Video2.style.display = "none";
}
}
</script>
<video id="Video1" controls="" width="320" height="240">
<source src="https://www.tdblog.it/wp-
content/uploads/2020/07/Video_aruba_200721_04.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<video id="Video2" controls="" style="display:none; float:right;"
width="320" height="240">
<source src="https://www.tdblog.it/wp-
content/uploads/2020/06/1160438711001_6017851885001_6017852130001.mp4"
type="video/mp4">
Your browser does not support the video tag.
</video>
You forgot the if statement plus you need to get the video2 element.
document.getElementById('Video1').addEventListener('ended', myHandler, false);
function myHandler(e) {
var video2 = document.getElementById("Video2");
if (video2.style.display === "none") {
video2.style.display = "block";
localStorage.setItem('video1Completed', 'true');
} else {
}
}
window.onload = function() {
var video2 = document.getElementById("Video2");
if (localStorage.getItem('video1Completed') == 'true') {
video2.style.display = "block";
} else {
video2.style.display = "none";
}
}

How to toggle audio play() pause() with a button click?

I have added an audio to my website, which is playing when site is opened. Now I want add play/pause button to toggle the audio.
This is how I tried it:
<audio id="myAudio" autoplay >
<source src="mp3/background-music.mp4" type='audio/mp4'>
Your user agent does not support the HTML5 Audio element.
</audio>
<a type="button" class="play-pause" title="play/pause"><i class="fa fa-pause"></i></a>
<script type="text/javascript">
$(document).ready(function() {
var playing = false;
$('a.audio-btn').click(function() {
if (playing == false) {
document.getElementById('myAudio').play();
playing = true;
$(this).text("stop sound");
} else {
document.getElementById('myAudio').pause();
playing = false;
$(this).text("restart sound");
}
});
});
</script>
But its not working for me. Can anybody tell me where I have gone wrong?
For demo purpose, i add video tag, to work with audio you can replace video to audio tag and Use
$('.play-pause')
Instead of
$('a.audio-btn')
For audio use this at the place of video tag :
<audio id="myAudio" autoplay>
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type='audio/mp4'>
Your user agent does not support the HTML5 Audio element.
</audio>
$(document).ready(function () {
var playing = true;
$('.play-pause').click(function () {
if (playing == false) {
document.getElementById('myAudio').play();
playing = true;
$(this).text("Sop Sound");
} else {
document.getElementById('myAudio').pause();
playing = false;
$(this).text("Restart Sound");
}
});
});
a {
background: #000;
color: #fff;
cursor: pointer;
padding: 10px;
}
video {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="myAudio" autoplay>
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type='video/mp4'>
Your user agent does not support the HTML5 Audio element.
</video>
<a type="button" class="play-pause" title="play/pause">Play / Pause</a>
Change your $('a.audio-btn') into $('a.play-pause').
What exactly is not working? Does the button not appear, does it not function?
I would suggest using something like the following:
var myAudio = document.getElementById("myAudio");
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause()
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};

Mute toggle on multiple audio playing at the same time

I'm trying to make an A/B test comparison for audio. It will be a "demo" version of a song and a real version.
I have them playing and stopping at the same time, but i can't work out the mute toggle. (i have it as two buttons now, but ideally i'd love to have one button that will mute one audio and unmute the other, and vice versa on reclick. Sorry i'm still learning js so any help would be awesome!)
I have what i have so far in a jsfiddle
https://jsfiddle.net/nickdulac/36r22svz/
html
<audio id="audio1" muted controls>
<source src="http://dl.dropbox.com/u/1538714/article_resources/cat.m4a" type="audio/mpeg" />
<source src="http://dl.dropbox.com/u/1538714/article_resources/cat.ogg" type="audio/ogg" />
</audio><br />
<audio id="audio2" controls>
<source src="http://dl.dropbox.com/u/1538714/article_resources/song.m4a" type="audio/mpeg" />
<source src="http://dl.dropbox.com/u/1538714/article_resources/song.ogg" type="audio/ogg" />
</audio><br />
<button onclick="play();">Play</button><br />
<button onclick="stop();">Stop</button><br />
<button onclick="mute1();">Mute 1</button><br />
<button onclick="mute2();">Mute 2</button><br />
js
var play = function() {
var audio1 = document.getElementById('audio1');
var audio2 = document.getElementById('audio2');
audio1.play();
audio2.play();
}
var stop = function() {
var audio1 = document.getElementById('audio1');
var audio2 = document.getElementById('audio2');
audio1.pause();
audio2.pause();
}
var mute1 = function() {
var audio1 = document.getElementById('audio1');
var audio2 = document.getElementById('audio2');
audio1.volume() = 1;
audio2.volume() = 0;
}
var mute2 = function() {
var audio1 = document.getElementById('audio1');
var audio2 = document.getElementById('audio2');
audio1.volume() = 0;
audio2.volume() = 1;
}
p.s. i have random audio in there for now!
Simply have a global variable. a flag that knows the current status and work accordingly. (ADDED MUTE)
Two different Mute buttons
Please check this fiddle : https://jsfiddle.net/36r22svz/6/
Single Mute Toggle
Please check this fiddle : https://jsfiddle.net/36r22svz/7/
HTML
<audio id="audio1" controls>
<source src="http://dl.dropbox.com/u/1538714/article_resources/cat.m4a" type="audio/mpeg" />
<source src="http://dl.dropbox.com/u/1538714/article_resources/cat.ogg" type="audio/ogg" />
</audio><br />
<audio id="audio2" controls>
<source src="http://dl.dropbox.com/u/1538714/article_resources/song.m4a" type="audio/mpeg" />
<source src="http://dl.dropbox.com/u/1538714/article_resources/song.ogg" type="audio/ogg" />
</audio><br />
<button onclick="play();" id="button1">Play</button><br />
<button onclick="mute();" id="button2">Mute</button><br />
JS
var audio1 = document.getElementById('audio1');
var audio2 = document.getElementById('audio2');
var button1 = document.getElementById('button1');
var isPlaying = false;
var muteToggle = true;
var play = function() {
if(!isPlaying){
button1.innerHTML = 'Pause';
audio1.play(); // this stream will immediately stop when the next line is run on iOS
audio2.play(); // this will stop audio1 on iOS
isPlaying = true;
} else {
button1.innerHTML = 'Play';
audio1.pause(); // this stream will immediately stop when the next line is run on iOS
audio2.pause(); // this will stop audio1 on iOS
isPlaying = false;
}
}
var mute = function(){
if(muteToggle){
muteToggle = false;
audio1.muted = true;
audio2.muted = false;
} else {
muteToggle = true;
audio2.muted = true;
audio1.muted = false;
}
}
I think adding this (very simple) funtion and calling to it from one button it should work.
Add this to your Javascript
var muted = 'on';
var button = document.getElementById(mutebut);
function muteorplay(){
if (muted == 'on'){
mute1()
muted='off';
button.innerHTML='Mute 1';
}else{
mute2()
muted='on';
button.innerHTML='Mute 2';
}
}
And replace the two mute buttons with this one
<button onclick="muteorplay();" id="mutebut">Mute 2</button><br />

How to loop sound in JavaScript?

I tried below code to play a sound in JavaScript for certain times but with no success, the sound plays just once, what is the problem?
for(var i = 0; i < errors; i++){
PlaySound3();
}
Function:
function PlaySound3() {
var audioElement = document.getElementById('beep');
audioElement.setAttribute("preload", "auto");
audioElement.autobuffer = true;
audioElement.load();
audioElement.play();
};
HTML code:
<audio id="beep">
<source src="assets/sound/beep.wav" type="audio/wav" />
</audio>
If you want to play the sound infinitely use the attribute loop in the tag audio :
<audio id="beep" loop>
<source src="assets/sound/beep.wav" type="audio/wav" />
</audio>
Edit
If you want to stop the loop after 3 times, add an event listener :
HTML:
<audio id="beep">
<source src="assets/sound/beep.wav" type="audio/wav" />
</audio>
JS:
var count = 1
document.getElementById('beep').addEventListener('ended', function(){
this.currentTime = 0;
if(count <= 3){
this.play();
}
count++;
}, false);

Play one HTML audio element at a time

I have many audio elements on a single page and I want to play just one element at a time. That is if one audio element is playing and I click on play on another element, the previous audio element should pause.
I found a jQuery code from another question to do this but that uses an image as play/pause controls. I'm using the inbuilt controls='controls' attribute for the audio element instead. Is it possible to use jQuery to control the play/pause feature for the audio element in my case?
Here is my HTML code
<div>
<p class="song"><h3><strong>#1 Intro - The Oath</strong></h3><p>
<audio class="playback" src=http://geo-samples.beatport.com/lofi/5005876.LOFI.mp3 controls='controls' preload="none">
<I>Your browser does not support the audio element.</I>
</audio>
</div>
<div>
<p class="song"><h3><strong>#2 A State Of Trance Year Mix 2013</strong></h3></p>
<audio class="playback" src=http://geo-samples.beatport.com/lofi/5005933.LOFI.mp3 controls='controls' preload="none">
<I>Your browser does not support the audio element.</I>
</audio>
</div>
Here is the jQuery code
$(document).ready(function() {
var curPlaying;
$(function() {
$(".playback").click(function(e) {
e.preventDefault();
var song = $(this).next('audio')[0];
if(song.paused){
song.play();
if(curPlaying) $("audio", "#"+curPlaying)[0].pause();
} else { song.pause(); }
curPlaying = $(this).parent()[0].id;
});
});
});
The jQuery code doesn't seem to be working for me.
$(function(){
$("audio").on("play", function() {
$("audio").not(this).each(function(index, audio) {
audio.pause();
});
});
});
See sample at JSFiddle
Vanilla JS solution
Here's a solution that doesn't require jQuery.
function onlyPlayOneIn(container) {
container.addEventListener("play", function(event) {
audio_elements = container.getElementsByTagName("audio")
for(i=0; i < audio_elements.length; i++) {
audio_element = audio_elements[i];
if (audio_element !== event.target) {
audio_element.pause();
}
}
}, true);
}
document.addEventListener("DOMContentLoaded", function() {
onlyPlayOneIn(document.body);
});
Some things to note:
Because this listens for events on a parent element, not on the audio elements themselves, they can be added or removed after the page is loaded and it will still work.
It watches for the play event in the capture phase because play events don't bubble.
More media events are described here on MDN.
Listening for "DOMContentLoaded" should work for most browers.
Little Modification to LostInComputer's Answer
In Your HTML Write:
<audio controls onplay="pauseOthers(this);" >
<source src="SourcePath">
</audio>
In Js Write:
function pauseOthers(ele) {
$("audio").not(ele).each(function (index, audio) {
audio.pause();
});
}
Assuming that your syntax for stopping and pausing tracks is correct (I don't know anything about the audio element), you should be able to do something like this:
$(".playback").click(function(e) {
// pause all other tracks
$('.audio').each(function () {
var song = this;
if (!song.paused) { song.pause(); }
});
// play the audio associated with this element
this.play();
});
<script>
function controlplay(e) {
document.querySelectorAll('.playback').forEach(item => { if(item.id != e.target.id) item.pause(); });
}
</script>
<script>
document.querySelectorAll('.').forEach(item => { item.addEventListener("play", event => { controlplay(event) })});
</script>
Angular:
<audio (play)="audioPlay($event)" controls preload="none">
<source [src]="url" type="audio/mpeg">
</audio>
audioPlay(e) {
let eAudio = this.domService.getDocument.getElementsByTagName('audio')
if (eAudio && eAudio.length > 0) {
for (var i = 0; i < eAudio.length; i++) {
if(e.target !== eAudio[i]){
eAudio[i].pause();
}
}
}
}
<script>
var nowplaying = null;
// Pause and reset playing audio before starting new selection
function pauseRunningAudio(id) {
if ( nowplaying != null && nowplaying != id) {
var x = document.getElementById(nowplaying);
x.pause();
x.load();
}
nowplaying = id;
}
</script>
<!-- id and function value must be the same -->
<audio controls onplay="pauseRunningAudio('song1')" id="song1">
<source src="Bohemian Rhapsody.mp3" type="audio/mpeg">
</audio>
<audio controls onplay="pauseRunningAudio('song2')" id="song2">
<source src="November Rain.mp3" type="audio/mpeg">
</audio>
<audio controls onplay="pauseRunningAudio('song3')" id="song3">
<source src="Smoke on the Water.mp3" type="audio/mpeg">
</audio>

Categories

Resources