Preventing simultaneous playing of HTML5 Video and Audio elements - javascript

Using HTML5 I have 2 Audio elements and 1 video element on a page.
Quite simply I'd like to add JavaScript functionality that prevents them from being played simultaneosly.
My main problem is how to target the click events of the default player.
The HTML is below, thanks;
<section id="mp3Section">
<h2>MUSIC</h2>
<ul>
<li>Lovers Pass<audio id="audioLP" controls="controls" preload="auto" autobuffer>
<p class="redText">Sorry. Your browser does not support this audio element</p>
<source src="music/loversPass.mp3" />
<source src="music/loversPass.wav" />
</audio></li>
<li>All The Fun<audio id="audioATF" controls="controls" preload="auto" autobuffer="autobuffer">
<p class="redText">Sorry. Your browser does not support this audio element</p>
<source src="music/allTheFun.mp3" />
<source src="music/allTheFun.wav" />
</audio></li>
</ul>
</section>
<section id="videoSection">
<h2>Video</h2>
<video id="vidScreen" controls poster="images/vidThumb.jpg">
<source src="videos/loversPassOGV.ogg"/>
<source src="videos/loversPassVid.mp4" />
</video>
</section>

How I'd do it (using jQuery for simplicity, though not required):
$('audio,video').bind('play', function() {
activated = this;
$('audio,video').each(function() {
if(this != activated) this.pause();
});
});

The audio and video elements have events that you can catch. See for example https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox .
You could probably do something like this (untested):
var allMediaIds = ["audioLP", "audioATF", "vidScreen"];
var allMedia = [];
for (var i = 0, len = allMediaIds.length; i < len; i++) {
allMedia.push(document.getElementById(allMediaIds[i]));
}
function loopAllMedia(callback) {
for (var i = 0, len = allMedia .length; i < len; i++) {
callback(allMedia[i]);
}
}
loopAllMedia(function(element) {
element.addEventListener("play", function() {
loopAllMedia(function(otherElement) {
if (element != otherElement)
otherElement.pause();
});
});
});

Related

Plyr.js - Events not implementing on multiple video element

I have apply plyr.js with play and pause events to automatically enter and exit fullscreen respectively.
but the events methods not working on multiple videos it only works when I apply single video.
HTML
<div class="video-container mini-canvas">
<video id="player" playsinline class="js-player">
<source src="./background-image3.mp4" type="video/mp4" />
</video>
</div>
<div class="video-container mini-canvas">
<video id="player" playsinline class="js-player">
<source src="./background-image3.mp4" type="video/mp4" />
</video>
</div>
JS
const players = Array.from(document.querySelectorAll('.js-player')).map(p => new Plyr(p, {
clickToPlay: true,
}));
players.on('play', function() {
console.log('Play')
players.fullscreen.enter();
document.querySelector('.video-container').classList.remove('mini-canvas')
})
players.on('pause', function() {
console.log('Pause')
players.fullscreen.exit();
document.querySelector('.video-container').classList.add('mini-canvas')
})
CSS
.video-container {
width: 150px;
margin: 0 auto;
}
.video-container.mini-canvas > .plyr {
filter: blur(2px);
}
.video-container.mini-canvas .plyr__controls {
display: none;
}
Below is the link to download HTML file
https://github.com/Yusufzai/issue-plyer.js-github.git
Any help would be appreciated
It took me some time but I figure out my mistake what I am doing wrong.
I am not implementing it in the loop to extract those values
for (let index = 0; index < players.length; index++) {
players[index].on('play', function() {
console.log('Play')
players[index].fullscreen.enter();
document.querySelector('.video-container').classList.remove('mini-canvas')
})
players[index].on('pause', function() {
console.log('Pause')
players[index].fullscreen.exit();
document.querySelector('.video-container').classList.add('mini-canvas')
})
}

Stop a video when another one is clicked

I have two locally hosted videos on the same page. I am trying to stop one once another is clicked, but it does not work.
<div class="banner has-hover has-video is-full-height is-selected" id="banner-1353813713" style="position: absolute; left: 0%;">
<div class="banner-inner fill">
<div class="banner-bg fill">
<div class="bg fill bg-fill "></div>
<div class="video-overlay no-click fill visible"></div>
<video class="video-bg fill visible" preload="" playsinline="" autoplay="" muted="" loop=""> <source src="https://www.exampledomain/video1.mp4" type="video/mp4"></video> </div>
<div class="banner-layers container">
<div class="fill banner-link"></div>
<div id="text-box-585511097" class="text-box banner-layer x10 md-x10 lg-x10 y35 md-y35 lg-y35 res-text">
<div class="text-box-content text dark">
<div class="text-inner text-center">
<a href="/offers/" target="_self" class="button white is-outline is-large offersbutton hidden" style="border-radius:1px;">
<span>View Video</span> </a>
<a href="/offers/" target="_self" class="button white is-outline is-large offersbutton hidden" style="border-radius:1px;">
<span>Offers</span></a>
<div class="video-button-wrapper" style="font-size:70%"><i class="icon-play" style="font-size:1.5em;"></i></div>
<p>Click to view full video</p>
</div>
</div>
I have tried listening to the classes onlick, but it has not worked:
<script>
$(".video-bg fill visible").on("click", function() {
// All but not this one - pause
$(".video-bg fill visible").not( this ).each(function() {
this.pause();
});
// Play this one
// this.play();
// Or rather toggle play / pause
this[this.paused ? "play" : "pause"]();
});
</script>
Here is a simple POC using vannila JS relying on play event. You can also use load() instead of pause() to start the video from beginning (instead of just pausing).
Reference https://www.w3schools.com/tags/ref_av_dom.asp
// assume only one video is playing at a time
var videoPlaying = null;
const onPlay = function() {
if (videoPlaying && videoPlaying != this) {
videoPlaying.pause()
}
videoPlaying = this
}
// init event handler
const videos = document.getElementsByClassName("video-bg")
for (let i = 0; i < videos.length; i++) {
videos[i].addEventListener("play", onPlay)
}
<video id="video-1" class="video-bg" width="320" height="240" controls>
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<video id="video-2" class="video-bg" width="320" height="240" controls>
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
If you only want that one video should pause when another is played this might help. Note: I am not using any style except for video's height and width . This code rely on onplay call from html and pause()
function playVideo1() {
document.getElementById('video2').pause();
}
function playVideo2() {
document.getElementById('video1').pause();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Stop either</title>
<style>
#video1 {
height: 200px;
width: 200px;
float: left;
}
#video2 {
height: 200px;
width: 200px;
float: right;
}
</style>
</head>
<body>
<video controls id="video1" onplay="playVideo1();"><source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4"></video>
<video controls id="video2" onplay="playVideo2();"><source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4" type="video/mp4"></video>
<script type="text/javascript" src="a.js"></script>
</body>
</html>
Video are from here and here i am not responsible for them.
Hi tested a theory but you'll have to create buttons to play/pause
theory => do a .each on all video tags
this code below : when you click the words PLAY => it will pause the other video if it's playing
like this
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" ></script>
<script>
function pause_all_videos () { $("video").each(function() { this.pause(); }); }
function playonly (vid) { pause_all_videos(); document.getElementById(vid).play(); }
</script>
<style>
div{padding:3px;margin:3px;}
</style>
<div>
<video id="v1" controls src="https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4" ></video>
<div><span onclick="playonly('v1');" >PLAY</span> ----- <span onclick="pause_all_videos();" >PAUSE</span></div>
</div>
<hr>
<div>
<video id="v2" controls src="https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_640_3MG.mp4" ></video>
<div><span onclick="playonly('v2');" >PLAY</span> ----- <span onclick="pause_all_videos();" >PAUSE</span></div>
</div>
You can do this by taking the video tag and the pause method.
function videoone() {
document.getElementById("videotwo").pause();
document.getElementById("videothree").pause();
document.getElementById("videofour").pause();
}
In the code above, the name of the verb related to onplay is in the video tag
// assume only one video is playing at a time
var videoPlaying = null;
const onPlay = function() {
if (videoPlaying && videoPlaying != this) {
videoPlaying.pause()
}
videoPlaying = this
}
// init event handler
const videos = document.getElementsByClassName("video-bg")
for (let i = 0; i < videos.length; i++) {
videos[i].addEventListener("play", onPlay)
}
<video id="video-1" class="video-bg" width="320" height="240" controls>
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<video id="video-2" class="video-bg" width="320" height="240" controls>
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>

Display Video Duration in mm:ss Format

Thanks to Saar Davidson(This Answer) we know how to display duration of multiple videos on the page.
But, how can I convert the seconds shown to mm:ss format?!
here is the code which displays duration of video in seconds:
var videos = document.querySelectorAll(".mhdividdur");
var durationsEl = document.querySelectorAll(".mhdi_video_duration");
for(let i = 0; i < videos.length; i++) {
videos[i].onloadedmetadata = function() {
durationsEl[i].innerHTML = videos[i].duration;
};
}
<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//hwasa.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>
<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//numb.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>
There is NO NEED of any library. I have Updated the code.
Check it out:
var videos = document.querySelectorAll(".mhdividdur");
var durationsEl = document.querySelectorAll(".mhdi_video_duration");
for(let i = 0; i < videos.length; i++) {
videos[i].onloadedmetadata = function() {
var mzminutes = Math.floor(videos[i].duration / 60);
var mzseconds = Math.floor(videos[i].duration - (mzminutes * 60));
durationsEl[i].innerHTML = mzminutes+':'+mzseconds;
};
}
<video class="mhdividdur" width="240px" controls preload="metadata">
<source src="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-576p.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>
<video class="mhdividdur" width="240px" controls preload="metadata">
<source src="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-576p.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>
thank you Saar Davidson for the hints :)

How can I pass the id of an element in the addEventListener?

How can I get the id from many play buttons ?
I just get the last element when I alert the order.
I want do in the end something like:
videos[id].play();
instead of
video.play();
window.addEventListener("load", function(event) {
var videos = document.getElementsByTagName("video");
var btnsPlay = document.getElementsByClassName("btnPlay");
for (var i = 0; i < videos.length; i++)
{
var video = videos[i];
var btnPlay = btnsPlay[i];
// … find button objects and add listener …
btnPlay.addEventListener("click", function (event) {
var id = i;
video.play();
alert(id);
}); // …
}
});
<!DOCTYPE HTML>
<html lang="de">
<head>
<meta charset="utf-8">
</head>
<body>
<video width="20%" height="240" controls>
<source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
<source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
<source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
<source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
Your browser does not support the video tag.
</video>
<div class ="controlbtn">
<button class="btnPlay">Play</button>
</div>
<video width="20%" height="240" controls>
<source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
<source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
<source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
<source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
Your browser does not support the video tag.
</video>
<div class ="controlbtn">
<button class="btnPlay">Play</button>
</div>
<video width="20%" height="240" controls>
<source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
<source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
<source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
<source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
Your browser does not support the video tag.
</video>
<div class ="controlbtn">
<button class="btnPlay">Play</button>
</div>
</body>
</html>
Try changing
for (var i = 0; i < videos.length; i++)
To
for (let i = 0; i < videos.length; i++)
The reason this problem is happening is because when the function is being invoked the value of i has already changed. You need to use let to have it saved at the block scope level and not at the function scope level

html5 videojs playlist setup

I want to implement videojs player on a sharepoint site. I have been able to setup the video player with one static video source for the player. Now I want to have a list of video urls on the side of the player, which user can click on and load the video on the same player. Something close has been done here: http://jsfiddle.net/Barzi/Jzs6B/9/ but without using videojs.
How can I do something similar with videojs implementation? http://jsfiddle.net/6nJ4z/
<div id="html5videoplayer" style="font-family: Arial Unicode MS;">
<video id="videoarea" class="video-js vjs-default-skin" controls preload="none" data-setup="{}">
<!--<source src="http://video-js.zencoder.com/oceans-clip.mp4" type='video/mp4' />-->
</video>
</div>
<ul id="playlist">
<li>Happy Fit</li>
<li>Sintel</li>
<li>Big Buck Bunny</li>
</ul>
HTML
<div id="html5videoplayer" style="font-family: Arial Unicode MS;">
<video id="videoarea" class="video-js vjs-default-skin" controls preload="none" data-setup="{}">
<source src="http://video-js.zencoder.com/oceans-clip.mp4" type="video/mp4" />
</video>
</div>
<ul id="playlist">
<li data-loc="http://video-js.zencoder.com/oceans-clip.mp4" data-type="video/mp4">Oceans</li>
<li data-loc="http://html5videoformatconverter.com/data/images/happyfit2.mp4" data-type="video/mp4">Happy Feet</li>
<li data-loc="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" data-type="video/mp4">Sintel</li>
<li data-loc="http://www.ioncannon.net/examples/vp8-webm/big_buck_bunny_480p.webm" data-type="video/webm">Big Buck Bunny</li>
</ul>
CSS
#playlist li {
color: blue;
text-decoration: underline;
}
#playlist li:hover {
color: black;
cursor: pointer;
}
Javascript
function doPlayList(listID, playerID) {
var player = document.getElementById(playerID);
var video = player.getElementsByTagName("video")[0];
var s;
video.src = null;
video.setAttribute("data-count", 0);
video.addEventListener("ended", function (e) {
e.preventDefault();
s = this.getElementsByTagName("source")[0];
var c = parseInt(this.getAttribute("data-count")) + 1;
var item = document.getElementById("video" + c);
if (item === null) {
item = document.getElementById("video0");
c = 0;
}
s.src = item.getAttribute("data-loc");
s.type = item.getAttribute("data-type");
this.setAttribute("data-count", c);
this.setAttribute("autoplay", "autoplay");
this.load();
this.play();
});
var list = document.getElementById(listID);
var items = list.getElementsByTagName("li");
for (var i = 0; i < items.length; i++) {
var item = items[i];
item.id = "video" + i;
item.addEventListener("click", function (e) {
e.preventDefault();
var p = document.getElementById("html5videoplayer");
var v = p.getElementsByTagName("video")[0];
var s = p.getElementsByTagName("source")[0];
s.src = this.getAttribute("data-loc");
s.setAttribute("type", this.getAttribute("data-type"));
v.setAttribute("data-count", this.id.substr(5));
v.setAttribute("autoplay", "autoplay");
v.load();
v.play();
});
}
}
document.onready = doPlayList("playlist", "html5videoplayer");
Try it out in a jsFiddle.
Obviously the difference, here, no jQuery required. Let me know if you have any questions.
EDIT: Changed the code so it uses the source element and data-* attributes. Hope this helps.
You can change the video in video tag with javascript. You can remove the href and use the element onclick with the adress of video, for example:
<div id="html5videoplayer" style="font-family: Arial Unicode MS;">
<video id="videoarea" class="video-js vjs-default-skin" controls preload="none" data-setup="{}">
<source src="http://video-js.zencoder.com/oceans-clip.mp4" type='video/mp4' />
</video>
</div>
<ul id="playlist">
<li>Happy Fit 2</li>
<li>Happy Fit 3</li>
<li>Happy Fit 4</li>
</ul>
<script type="text/javascript">
var PlayVideo = function(videoSrc){
$("#html5videoplayer").remove("source");
var htmlVideo = '<source type="video/mp4" src="'+ videoSrc +'" />';
$("#html5videoplayer").html(htmlVideo);
}
</script>
Found this github project, works really well!. Have a look at it.
https://github.com/cfx/videojs-playlist

Categories