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);
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;
});
}
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
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();
}
});
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