Toogle icon (play/pause), and stop when another button is clicked - javascript

Hope this post is not doubled, since i've search a lot for my same question and i surely found some but none of them really helped me.
I just need to 'mix' the scripts i found so i get what i need, let me explain better with my code:
Script for play a song and stop when another is clicked (but no pause if i click the same button)
var currentsound;
function play_pause(player) {
if(currentsound)
{
currentsound.pause();
}
var myAudio = document.getElementById(player);
myAudio.play();
currentsound = myAudio;
myAudio.currentTime = 0;
}
And this is another script i found here for toogle the icon :
var play = false;
function toggle() {
var image = document.getElementById('image')
var scan = document.getElementById('scan');
play = !play;
if (play) {
image.src = "pause.png";
scan.play();
}
else {
image.src = "play.png";
scan.pause();
}
}
HTML PART:
<audio preload="none" id="myAudio2" src="rosina2.mp3" type="audio/mpeg"> </audio>
<img src="play.png" width=30 height=30 border="0"
onclick="play_pause('myAudio2')" id="image">
</p></td>
<td width="29%" class="bonuspointstyle11"><p align="center"> 2 </p></td>
<td width="58%" class="bonuspointstyle11"><p class="bonuspointstyle5"> Istanpitta</p></td>
</tr>
<tr>
<td width="13%" class="bonuspointstyle11"><p>
<center>
<audio preload="none" id="myAudio3" src="rosina3.mp3" type="audio/mpeg"> </audio>
<img src="play.png" onclick="play_pause('myAudio3')"; width=30 height=30 border="0" >
</center>
</p></td>
<td width="29%" class="bonuspointstyle11"><p align="center"> 3 </p></td>
<td width="58%" class="bonuspointstyle11"><p class="bonuspointstyle5"> Gaetta </p></td>
</tr>
<tr>
<td width="13%" class="bonuspointstyle11"><p>
<center>
<audio preload="none" id="myAudio4" src="rosina2.mp3" type="audio/mpeg"> </audio>
<img src="play.png" onclick="play_pause('myAudio4')"; width=30 height=30 border="0" >
</center>
</p></td>
<td width="29%" class="bonuspointstyle11"><p align="center"> 4 </p></td>
<td width="58%" class="bonuspointstyle11"><p class="bonuspointstyle5">TEST </p></td>
</tr>
Im looking to get a simple play/pause button that toggle when clicked (to play image to pause image of course) and if any other button is clicked the last one gets stopped and start to sound the new one.
How can i toggle for more than once? In the answer i've got 1 which envolve calling the fuction i have but it's the same as only the first button toggle (even when i clicked on any other button)
Edit: Even if anybody can tell me how to make a script for only toggling any amount of buttons you have indiviually, i'd be grateful
I'd really really appreciate any kind of comment/advice that lead me to get my code running as i want. Thanks
Best regards

I suppose your first code is wrong:
var currentsound;
function play_pause(player) {
if (currentsound) {
currentsound.pause();
currentsound = null; // currentsound should be reset and return from functions to prevent playing again
return;
}
var myAudio = document.getElementById(player);
myAudio.play();
currentsound = myAudio;
myAudio.currentTime = 0;
//myAudio.play(); // duplicated code
}
To toggle an image it's not nessasary to mix the code. Just call the second functions from first one with some modifications:
function toggleIcon(playing) {
var image = document.getElementById('image')
if (playing) {
image.src = "play.png";
} else {
image.src = "pause.png";
}
}
And call it from first function:
function play_pause(player) {
if (currentsound) {
currentsound.pause();
currentsound = null;
toggleIcon(false); // <----- toggleIcon false
return;
}
var myAudio = document.getElementById(player);
myAudio.play();
currentsound = myAudio;
myAudio.currentTime = 0;
toggleIcon(true); // <----- toggleIcon true
}
Or even better - use events pause and play and do not touch play_pause function:
document.getElementById("myAudio2").onpause = function() {
toggleIcon(false);
};
document.getElementById("myAudio2").onplay = function() {
toggleIcon(true);
};

Well, after a lot of research i could get something that for now it's ok for me.
I just want to share if anybody else gets my same problem
This are my scripts (i needed to use 2)
<script language="javascript">
var currentsound;
function play_pause(player) {
var myAudio = document.getElementById(player);
if(myAudio.paused) {
myAudio.play();
} else{
myAudio.pause();
}
}
function changeImage(img) {
var imgfile = img.src.split(/\s+/).pop();
if (imgfile =="http://www.../.../pause.png" )
{
img.src = "http://www.../.../play.png";
}
else
{
img.src = "http://www.../.../pause.png";
}
}
</script>
And what basically do is that the first function do a play/pause for each button, and 2nd function toggle the image (see the onclick event)
This is my HTML:
<audio preload="none" id="myAudio1" src="http://www.../.../Music1.mp3" type="audio/mpeg"> </audio>
<img src="http://www.../.../play.png" width=30 height=30 border="0"
onclick="play_pause('myAudio1');changeImage(this)"> <!--id needs to be changed manually (id and onclick event) -->
<audio preload="none" id="myAudio2" src="http://www.../.../Music2.mp3" type="audio/mpeg"> </audio>
<img src="http://www.../.../play.png" width=30 height=30 border="0"
onclick="play_pause('myAudio2');changeImage(this)">
Indeed is not the best solution, because every time you click on another button (different from the one is running) them both will sound at same time, but at least you can play/pause each button individually and toggle the icons too.
For more button just copy-paste the html part and change the id part
Hope is usefull for anyone else than me, and if you got a better answer like having a counter variable for put into the ID so don't need to be changed manually or playing/pause and stopping when any other button gets click, post it, will be very appreciate it!
Regards

Use this script like this so you can toggle images and stop the audio also
<script>
function audios1(img,player) {
var image = document.getElementById(img);
var audio = document.getElementById(player);
var otherimage = document.getElementsByTagName('img');
for(var i = 0, len = otherimage.length; i < len;i++){
if(otherimage[i] != image){
otherimage[i].src= "start4.png";
}
}
if (image.src.match("start4.png")) {
image.src = "stop.png";
audio.play();
} else {
image.src = "start4.png";
audio.pause();
}
audio.addEventListener("ended", function() {
audio.currentTime = 0;
image.src = "start4.png";
});
}
function audios2(img,player) {
var image = document.getElementById(img);
var audio = document.getElementById(player);
var otherimage = document.getElementsByTagName('img');
for(var i = 0, len = otherimage.length; i < len;i++){
if(otherimage[i] != image){
otherimage[i].src= "start4.png";
}
}
if (image.src.match("start4.png")) {
image.src = "stop.png";
audio.play();
} else {
image.src = "start4.png";
audio.pause();
}
audio.addEventListener("ended", function() {
audio.currentTime = 0;
image.src = "start4.png";
});
}
document.addEventListener('play', function(e){
var audios = document.getElementsByTagName('audio');
for(var i = 0, len = audios.length; i < len;i++){
if(audios[i] != e.target){
audios[i].pause();
audios[i].currentTime = 0;
}
}
},true);
</script>

Related

How can I play only one song on a page [duplicate]

I have 10 audio players with simple html audio tags on a html5 page.
No jquery, no special audio js plugins, etc...
Does anyone has a simple script in js to pause all other players when the current player is playing ?
I don't want to use js plugins because i want to keep a simple audio html code.
you can use event delegation. Simply listen to the play event in the capturing phase and then pause all video file, but not the target one:
document.addEventListener('play', function(e){
var audios = document.getElementsByTagName('audio');
for(var i = 0, len = audios.length; i < len;i++){
if(audios[i] != e.target){
audios[i].pause();
}
}
}, true);
Instead of looping over all audio tags on a page and pausing them, you can store a reference to the currently playing element, and have only that one pause when playing another.
document.addEventListener("play", function(evt) {
if(this.$AudioPlaying && this.$AudioPlaying !== evt.target) {
this.$AudioPlaying.pause();
}
this.$AudioPlaying = evt.target;
}, true);
Mixing both previous answers that didn't work, i've used that. I just added && window.$_currentlyPlaying != evt.target and all is working.
Also i've created a gist with this and other goodies for audio tags. javascript-audio-tags
window.addEventListener("play", function(evt)
{
if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
{
window.$_currentlyPlaying.pause();
}
window.$_currentlyPlaying = evt.target;
}, true);
$("audio").on("play", function() {
var id = $(this).attr('id');
$("audio").not(this).each(function(index, audio) {
audio.pause();
});
});
$("video").on("play", function() {
var id = $(this).attr('id');
$("video").not(this).each(function(index, video) {
video.pause();
});
});
I don't know if it is because of Chrome updates, but the previous answers did not work for me. I modified a bit of the code here and came up with this:
document.addEventListener("play", function(evt)
{
if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
{
window.$_currentlyPlaying.pause();
}
window.$_currentlyPlaying = evt.target;
}, true);
I don't know why, but the widow.addEventListener was not working for me, but I liked the idea of having the currentPlaying variable stored in the window element instead of having to create it outside of the listener prior to using it.
I made a player at the bottom and changed the src every time the user clicks on play
this is just one way of doing it
HTML
<audio src="tracks/track1.mp3" type="audio/mp3" class='audios'></audio>
<i class='fas fa-play'></i>
<i class='far fa-pause-circle'></i>
<i class='fas fa-stop'></i>
<audio src="tracks/track2.mp3" type="audio/mp3" class='audios'></audio>
<i class='fas fa-play'></i>
<i class='far fa-pause-circle'></i>
<i class='fas fa-stop'></i>
<audio src="tracks/track3.mp3" type="audio/mp3" class='audios'></audio>
<i class='fas fa-play'></i>
<i class='far fa-pause-circle'></i>
<i class='fas fa-stop'></i>
<audio class='main-audio' controls>
<source src="#" type="audio/mp3">
</audio>
JavaScript
const audios_with_src = document.querySelectorAll('.audios')
const play = document.querySelectorAll('.fa-play')
const pause = document.querySelectorAll('.fa-pause-circle')
const stop = document.querySelectorAll('.fa-stop')
const main_player = document.querySelector('.main-audio')
for(let i =0; i < audios_with_src.length; i++) {
play[i].addEventListener('click', (e) => {
main_player.src = audios_with_src[i].src;
main_player.play()
})
pause[i].addEventListener('click', () => {
main_player.pause()
})
stop[i].addEventListener('click', () => {
main_player.pause()
main_player.currentTime = 0; // there is no stop() function so had to do this
})
}
Best solution rewritten regarding ECMA 2022:
document.addEventListener('play', (event) => {
const audios = [...document.getElementsByTagName('audio')];
audios.forEach((audio) => audio !== event.target && audio.pause());
}, true);
You can even try this solution, if you don't want to loop through
var previousAudio;
document.addEventListener('play', function(e){
if(previousAudio && previousAudio != e.target){
previousAudio.pause();
}
previousAudio = e.target;
}, true);

Custom Controls for HTML5 Videos don't work

I am customising a video in html and css. So far the play button works and the full screen mode works too. But if I try to drag the slider (the one next to PLAY button) it is meant to change the position in the video too. Same with the volume button (next to MUTE button) - it doesn’t work if I try to slide it.
I wonder what is wrong with my code as I was partially following a tutorial and that’s the way they used for the tutorial.
<div id="video-container">
<!-- Video -->
<video id="video-container__video" width="640" height="365">
<source src='_assets/media/big_buck_bunny.mp4' type='video/mp4'>
</video>
<!-- Video Controls -->
<div id="video-controls">
<button type="button" id="video-controls__play-pause">Play</button>
<input type="range" id="video-controls__seek-bar" value="0">
<button type="button" id="video-controls__mute">Mute</button>
<input type="range" id="video-controls__volume-bar" min="0" max="1" step="0.1" value="1">
<button type="button" id="video-controls__full-screen">Full-Screen</button>
</div>
window.onload = function() {
//video
var video = document.getElementById("video-container__video");
//Buttons
var playButton = document.getElementById("video-controls__play-pause");
var muteButton = document.getElementById("video-controls__mute");
var fullScreenButton = document.getElementById("video-controls__full-screen");
//sliders
var seekBar = document.getElementById("video-controls__seek-bar");
var volumeBar = document.getElementById("video-controls__volume-bar");
//event listener for the play and pause button
playButton.addEventListener("click", function() {
if (video.paused == true) {
video.play();
//button text will change to Pause
playButton.innerHTML = "Pause";
} else {
//pause the video
video.pause();
//button will update its text to play
playButton.innerHTML = "Play";
}
});
// Event listener for the full-screen button
fullScreenButton.addEventListener("click", function() {
if (video.requestFullscreen) {
video.requestFullscreen();
} else if (video.mozRequestFullScreen) {
video.mozRequestFullScreen(); // Firefox
} else if (video.webkitRequestFullscreen) {
video.webkitRequestFullscreen(); // Chrome and Safari
}
});
//event listener for the change bar
seekBar.addEventListener("change", function() {
//calculate the new time
var time = video.duration * (seekBar.value / 100);
//update the video time
video.currentTime = time;
});
//the change bar will move as the video plays
video.addEventListener("timeupdate", function() {
//Calculate the slider value
var value = (100 / video.duration) * video.currentTime;
//Update the slider value
seekBar.value = value;
})
//pause the video when the slider handle is being dragged
seekBar.addEventListener("mousedown", function() {
video.pause();
});
//play the video when the
seekBar.addEventListener("mouseup", function() {
video.play();
});
volumeBar.addEventListener("change", function() {
//update the video volume
video.volume = volumeBar.value;
});
}

how loop video with javascript?

i have some videos source. I want to play it again when the last video is over. I tried this code below,but after the last ended it wont start from the beginning.
Here's my code below
HTML
<video id="myVideo" width="800" height="600" controls>
Your browser does not support HTML5 video.
</video>
JAVASCRIPT
<script>
var videoSource = new Array();
videoSource[0]='video/adsfsaf.mp4';
videoSource[1]='video/2.mp4';
videoSource[2]='video/1.mp4';
var videoCount = videoSource.length;
document.getElementById("myVideo").setAttribute("src",videoSource[0]);
function videoPlay(videoNum)
{
document.getElementById("myVideo").setAttribute("src",videoSource[videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
function videoBegin(videoNum)
{
document.getElementById("myVideo").setAttribute("src",videoSource[0]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
i = 0;
document.getElementById('myVideo').addEventListener('ended',myHandler,false);
function myHandler() {
i++;
if(i == (videoCount-1)){
// alert(i);
videoPlay(i);
}
else{
videoPlay(i);
}
}
</script
I found the solution.
function myHandler() {
i++;
if(i >= videoCount) i =0;
videoPlay(i);
}
Can't you use the "loop" attribute of the "video" element ?
W3School loop

Ending a video in HTML using JavaScript events?

I am displaying a YouTube video on my html page using JavaScript.
How do I hide the video and retain the page that displayed the video using JavaScript?
I need to hide the video on a button click.
My code looks like this:
function addVideo(qId){
alert("a video");
var $videoComp = '<div class="vid" id="myytplayer"><iframe id="ifr" width="560" height="315" src="//www.youtube.com/embed/ac7KhViaVqc" allowfullscreen=""></iframe></div><div class ="main"><button class="btn btn-success" id="one" >Close video</button></div>';
$('.create-elem').append($videoComp);
$(".main").click(function(){
//$(".vid").hide();
//$("#one").hide();
function stopthevideo(){
var myPlayer = document.getElementById('myytplayer');
myPlayer.stopVideo();
}
});
This is what I do to identify end of video.
var myVideo = document.getElementById("video1");
myVideo.addEventListener('ended',onVideoEnded,false);
function onVideoEnded(e) {
if(!e) { e = window.event; }
// Make your things here
hideVideo = true;
}
Or you can always try work with https://developers.google.com/youtube/js_api_reference#Playback_status
Hope one of these will help you :)
The try to set video position at the ended event:
Save the start time and duration time to variable after loadedmetadata event.
var myVideo = document.getElementById("video1");
var videoStartTime = 0;
var videoEndTime = 0;
myVideo.addEventListener('loadedmetadata', function() {
videoStartTime = 2;
videoEndTime = 4;
this.currentTime = videoStartTime;
}, false);
If current time is greater than start time plus end of video time, pauses the video.
myVideo.addEventListener('timeupdate', function() {
if(this.currentTime > videoStartTime + videoEndTime ){
this.pause();
}
});

Control multiple html5 audio tracks using a single controller

I am trying to implement a very minimal audio player for a web site.
The interface is rather simple. It has a play/pause button, and a mute/unmute button.
The problem I have is implementing multiple instances of the same player for different tracks.
The javascript for the player is:
jQuery(function() {
var myAudio = document.getElementById("myAudio");
var btnPlayPause = document.getElementById("btnPlayPause");
var btnMute = document.getElementById("btnMute");
btnPlayPause.addEventListener("click", function() {
if (myAudio.paused || myAudio.ended) {
myAudio.play();
btnPlayPause.innerHTML = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Play</span>";
}
else {
myAudio.pause();
btnPlayPause.innerHTML = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Pause</span>";
}
});
btnMute.addEventListener("click", function() {
if (myAudio.muted) {
myAudio.muted = false;
btnMute.innerHTML = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Mute</span>";
}
else {
myAudio.muted = true;
btnMute.innerHTML = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Unmute</span>";
}
});
});
This works fine for a single track. But if I have multiple tracks on the same page, this becomes a problem.
I am guessing that I need some modification to the syntax where I define the myAudio variable:
var myAudio = document.getElementById("myAudio");
However, I am not sure how to change that so the same script can control multiple audio tracks.
If possible, I also would like to be able to ensure that if the user clicks the play button on a different track, the track that is currently playing "stops" or is "paused" and the new track starts (so 2 tracks are not playing on top of each other).
This is jQuery based solution. To make HTML5 audio work also in IE8/7 use some additional flash fallback.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.10.1.js'></script>
<style type='text/css'>
.mp3Player {
padding:8px;
margin:8px;
background-color:#ddf;
}
</style>
<script type='text/javascript'>//<![CDATA[
jQuery(function (){
var myAudio = document.getElementById("myAudio");
var current = null;
var playingString = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Pause</span>";
var pausedString = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Play</span>";
$(document.body).on('click', '.btnPlayPause',function(e){
var target = this;
//console.log(target, current); //return;
if (current == target) {
target.innerHTML = pausedString;
target.parentNode.setAttribute('data-pos', myAudio.currentTime); //start from paused
myAudio.pause();
current = null;
} else { // current!=target
if (current != null) {
current.innerHTML = pausedString;
current.parentNode.setAttribute('data-pos', '0'); //reset position
target.parentNode.setAttribute('data-pos', myAudio.currentTime); //start from paused
}
current = target;
target.innerHTML = playingString;
if(myAudio.canPlayType && myAudio.canPlayType("audio/mpeg") != "") { // MP3
myAudio.src = target.parentNode.getAttribute('data-src');
} else if(myAudio.canPlayType && myAudio.canPlayType("audio/ogg") != "") { // OGG
myAudio.src = target.parentNode.getAttribute('data-src2');
} else {
return; // no audio support
}
myAudio.play();
myAudio.onloadeddata = function () {
myAudio.currentTime = parseFloat(target.parentNode.getAttribute('data-pos'));
};
}
});
$(document.body).on('click', '.btnMute',function(e){
myAudio.muted = !myAudio.muted;
$('.btnMute').each(function(){
if (myAudio.muted) {
this.innerHTML = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Muted</span>";
} else {
this.innerHTML = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Audible</span>";
}
});
});
});
//]]>
</script>
</head>
<body>
<audio id="myAudio"></audio>
<div class="mp3Player" data-src="a.mp3" data-src2="a.ogg" data-pos="0">
<button class="btnPlayPause button">►||</button>
<button class="btnMute button">MUTE</button>
<span class="infoLabel">Audio #1</span>
</div>
<div class="mp3Player" data-src="b.mp3" data-src2="b.ogg" data-pos="0">
<button class="btnPlayPause button">►||</button>
<button class="btnMute button">MUTE</button>
<span class="infoLabel">Audio #2</span>
</div>
</body>
</html>
jQuery code + result page.
javascript code + result page.
Both scripts need additional existing .mp3 files to play the sound

Categories

Resources