run 2 html video side by side at the same time JS - javascript

I would like to play 2 html video exactly at the same time (side-by-side).
I made a button which has a click EventListener on it. This listener trigger the 2 <video> tag to play it, but I think there is 150 ms a delay at the second play trigger.
index.html
<section>
<video src="source1" id="video1"></video>
<video src="source2" id="video2"></video>
<button id="play">Play</button>
</section>
and here is the basic script.js file.
const $video1 = document.getElementById('video1');
const $video2 = document.getElementById('video2');
const $play = document.getElementById('play');
const playVideo = () => {
$video1.play();
$video2.play();
};
$play.addEventListener('click', playVideo);
These 2 videos are almost the same, except the first video size is about 12MB and the other one is around 20MB
What I tried:
Tried to add a console.time('video') that could logs the delay between each play function call, but that can be different in each environment.

The only way I'm aware of about playing video in sync is to emit a custom event to sync the video in requestAnimationFrame:
var videos = {
a: Popcorn("#a"),
b: Popcorn("#b"),
},
scrub = $("#scrub"),
loadCount = 0,
events = "play pause timeupdate seeking".split(/\s+/g);
// iterate both media sources
Popcorn.forEach(videos, function(media, type) {
// when each is ready...
media.on("canplayall", function() {
// trigger a custom "sync" event
this.emit("sync");
// set the max value of the "scrubber"
scrub.attr("max", this.duration());
// Listen for the custom sync event...
}).on("sync", function() {
// Once both items are loaded, sync events
if (++loadCount == 2) {
// Iterate all events and trigger them on the video B
// whenever they occur on the video A
events.forEach(function(event) {
videos.a.on(event, function() {
// Avoid overkill events, trigger timeupdate manually
if (event === "timeupdate") {
if (!this.media.paused) {
return;
}
videos.b.emit("timeupdate");
// update scrubber
scrub.val(this.currentTime());
return;
}
if (event === "seeking") {
videos.b.currentTime(this.currentTime());
}
if (event === "play" || event === "pause") {
videos.b[event]();
}
});
});
}
});
});
scrub.bind("change", function() {
var val = this.value;
videos.a.currentTime(val);
videos.b.currentTime(val);
});
// With requestAnimationFrame, we can ensure that as
// frequently as the browser would allow,
// the video is resync'ed.
function sync() {
if (videos.b.media.readyState === 4) {
videos.b.currentTime(
videos.a.currentTime()
);
}
requestAnimationFrame(sync);
}
sync();
html{font-family:arial;}
<script src="https://static.bocoup.com/js/popcorn.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video height="180" width="300" id="a" controls>
<source src="https://videos.mozilla.org/serv/webmademovies/popcorntest.mp4"></source>
<source src="https://videos.mozilla.org/serv/webmademovies/popcorntest.ogv"></source>
<source src="https://videos.mozilla.org/serv/webmademovies/popcorntest.webm"></source>
</video>
<video height="180" width="300" id="b">
<source src="https://videos.mozilla.org/serv/webmademovies/popcorntest.mp4"></source>
<source src="https://videos.mozilla.org/serv/webmademovies/popcorntest.ogv"></source>
<source src="https://videos.mozilla.org/serv/webmademovies/popcorntest.webm"></source>
</video>
<input type="range" value="0" id="scrub" />
Ref: https://bocoup.com/blog/html5-video-synchronizing-playback-of-two-videos

UPDATE
Both of the answers was correct.
What I didn't know, that one of the video file has sound, and the other don't. That caused the 150ms delay.
Solved it with ffmpeg. Create an .mp3 file with the sound (and play it with <audio>), and 2 .mp4 files without sound.
They are playing exactly at the same time now.

I will also add this link here, as evident someone had a very similar problem, albeit with audio
Run function after audio is loaded
It appears you are looking for this event listener "canplaythrough", check more in the link.
function checkAudio() {
audioElem.setAttribute("src", audioFile);
audioElem.addEventListener('canplaythrough', (event) => {
resultScreen.innerHTML = "loaded audio";
});
}

Related

Can't stop the audio with Js

I have a problem with Javascript:
I want to stop the audio in a Js program when the game comes to an end. For this I define a variable "endGame" and I make it false, so that when I call it true in an event, the audio stops. But the problem is that the audio does not stop when this variable is set to true.
Here's the piece of code that I need some help with:
let endGame = false
main.addEventListener("click", (e) => {
themeSong.play()
if(endGame == true) {
themeSong.pause()
}
EventListeners will not be triggered when the variable change. You should do it manually.
let endGame = false;
main.addEventListener("click", (e) => {
themeSong.play();
});
// The function which updates the endGame variable and stop the audio
function fnEndGame() {
endGame = true;
themeSong.pause();
}
// You should call fnEndGame() to stop the game, DO NOT update the variable directly.
By using a custom event, and then throwing that event whenever you want, you can pause your music execution the moment you want to.
So instead of using an "endgame" variable, I suggest you throw a custom event named "supergame_endgame" and listen to that event, and halt all relevant audio's in that event listener.
See my comments in the code below for more explanation.
let audio = document.querySelector('audio');
let start = document.getElementById('play');
let stop = document.getElementById('stop');
/** simple starter of the sound **/
start.addEventListener('click', () => {
audio.play();
});
/** Event handler for own custom event, named `stop_my_audio_play`
* This will actually stop audio play, regardless from where the event `stop_my_audio_play` is
* cast from
*/
window.addEventListener('stop_my_audio_play', (e) => {
audio.pause();
});
/** Throw an event `stop_my_audio_play` with the attribute bubbles set to true
* So it can be caught at window level
*/
stop.addEventListener('click', () => {
stop.dispatchEvent(new Event('stop_my_audio_play', {bubbles:true}))
});
audio {
display:none;
}
<audio controls="controls" autobuffer="autobuffer" autoplay="autoplay" loop>
<source src="data:audio/wav;base64,UklGRhwMAABXQVZFZm10IBAAAAABAAEAgD4AAIA+AAABAAgAZGF0Ya4LAACAgICAgICAgICAgICAgICAgICAgICAgICAf3hxeH+AfXZ1eHx6dnR5fYGFgoOKi42aloubq6GOjI2Op7ythXJ0eYF5aV1AOFFib32HmZSHhpCalIiYi4SRkZaLfnhxaWptb21qaWBea2BRYmZTVmFgWFNXVVVhaGdbYGhZbXh1gXZ1goeIlot1k6yxtKaOkaWhq7KonKCZoaCjoKWuqqmurK6ztrO7tbTAvru/vb68vbW6vLGqsLOfm5yal5KKhoyBeHt2dXBnbmljVlJWUEBBPDw9Mi4zKRwhIBYaGRQcHBURGB0XFxwhGxocJSstMjg6PTc6PUxVV1lWV2JqaXN0coCHhIyPjpOenqWppK6xu72yxMu9us7Pw83Wy9nY29ve6OPr6uvs6ezu6ejk6erm3uPj3dbT1sjBzdDFuMHAt7m1r7W6qaCupJOTkpWPgHqAd3JrbGlnY1peX1hTUk9PTFRKR0RFQkRBRUVEQkdBPjs9Pzo6NT04Njs+PTxAPzo/Ojk6PEA5PUJAQD04PkRCREZLUk1KT1BRUVdXU1VRV1tZV1xgXltcXF9hXl9eY2VmZmlna3J0b3F3eHyBfX+JgIWJiouTlZCTmpybnqSgnqyrqrO3srK2uL2/u7jAwM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oGCgYKBgoGCgYKBgoGCgYKBgoGCgYKBgoGCgYKBgoGBgYCBgIGAgYCBgIGAgYCBgIGAgYCBgIGAgYCBgIGAgYCAgICBgIGAgYCBgIGAgYCBgIGAgYCBgExJU1RCAAAASU5GT0lDUkQMAAAAMjAwOC0wOS0yMQAASUVORwMAAAAgAAABSVNGVBYAAABTb255IFNvdW5kIEZvcmdlIDguMAAA" />
</audio>
<button id="play">Play</button>
<button id="stop">Stop</button>

How to start playing video by clicking on it without controls using React?

I use standart video html5 player in my react app:
const Video = ({ url, contentType }) => (
<video poster={url}>
<source src={`${url}#t=0.01`} type={contentType} className="video" />
</video>
)
and i would like to hide controls and play/pause video by clicking on it, i found how to do it by using javascript:
var overlay = document.getElementById('video-overlay');
var video = document.getElementById('video');
var videoPlaying = false;
overlay.onclick = function() {
if (videoPlaying) {
video.pause();
videoPlaying = false;
}
else {
video.play();
videoPlaying = true;
}
}
but i don't know how to replace it with react, i tried to add onClick{e => e.play} but it didn't work, also i checked what e contains, it doesn't contain any isPlaying flags or play/pause possibililties, please tell me how can i to it properly ?
There are two reasons that wouldn't work:
You didn't call play, you just referred to it. To call it, you'd need ().
The argument passed to an event handler isn't the element the event occurred on, it's an Event object (in React's case, a synthetic one). You can access the element you hooked the event on via the event's currentTarget property:
<video poster={url} onClick={e => e.currentTarget.play()}>
or with destructuring
<video poster={url} onClick={({currentTarget}) => currentTarget.play()}>

Run a function a few seconds before video ends using JavaScript

I have a video the being played. How can I call a function 5 seconds before the end of the video?
I thought to put a timer when I start the video, the problem is that the user can control the video, and stop it and play again how many times he wants, so the timer is getting ineffective.
Examples would be very nice!
-----EDIT-----
this is an example to a code i'm using:
video = document.createElement("video");
video.setAttribute("id", id);
video.src = url;
video.onended = function(e) {
var playlistName = getPlaylistName();
findNextSongToPlay(playlistName, playNextSong);
};
I want the "onended" event to be called not in the end, but 5 seconds before..
So I need to change it a little bit..
Again, Thanks a lot!
Here is a demo for you
Edit: Updated Demo.
window.onload=function(){
video = document.createElement("video");
video.setAttribute("id", "Myvideo");
video.setAttribute("controls", "controls");
video.src = "http://www.w3schools.com/html/mov_bbb.mp4";
video.addEventListener("timeupdate", myfunc,false);
document.body.appendChild(video);
}
function myfunc(){
if(this.currentTime > this.duration-5){
//Less than 5 seconds to go. Do something here.
//---- For Demo display purposes
document.getElementById('Example').innerHTML="Less than 5 seconds to go!";
//---------
} //End Of If condition.
//---- For Demo display purposes
else{document.getElementById('Example').innerHTML="";}
//---------
}
<div id="Example"></div>
Since your player is dynamically created you can use:
video = document.createElement("video");
video.setAttribute("id", id);
video.src = url;
//Add the event Listener
video.addEventListener("timeupdate", myfunc,false);
video.onended = function(e) {
var playlistName = getPlaylistName();
findNextSongToPlay(playlistName, playNextSong);
};
and that should call this function
function myfunc(){
if(this.currentTime > this.duration-5){
//Do something here..
}
}
If you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!
Sample with HTML5 player.
At most 100 milliseconds of difference can occur, not exactly 5 seconds.
But you can tune the script.
You can paste this code here to try it:
http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_video_all
<html>
<body>
<video id="vid" width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
<script>
var callOnce = true;
function monitorVideo() {
if ((vid.duration - vid.currentTime) < 5)
if (callOnce) {
myFunction();
callOnce = false;
}
}
function myFunction() {
console.log('5 seconds');
}
setInterval(monitorVideo, 100);
</script>
</body>
</html>
Tell us what video player you are using.
If it is custom put an id on part that says how far in to the video you are and say
if (document.getElementById("bla").innerhtml === whatever 5 seconds before the end of the video is)
function();

how to change vimeo video source to local mp4 video using javascript

I'm trying to make a video player which contains vimeo and local video but I'm dont know how to switch the video source to local video if the vimeo video fails to play.Im using video.js.any help please :)
here is my coding:
HTML
<video id="vid1" src="" class="video-js vjs-default-skin" controls preload="auto" width="640" height="360">
Javascript:
videojs('vid1', { "techOrder": ["vimeo"], "src": "https://vimeo.com/63186969" }).ready(function() {
// You can use the video.js events even though we use the vimeo controls
// As you can see here, we change the background to red when the video is paused and set it back when unpaused
this.on('pause', function() {
document.body.style.backgroundColor = 'red';
});
this.on('play', function() {
document.body.style.backgroundColor = '';
});
// You can also change the video when you want
// Here we cue a second video once the first is done
this.one('ended', function() {
this.src('http://video-js.zencoder.com/oceans-clip.mp4');
this.play();
});
i make some changes to my js but still unable to change.im new to javascript..please help me :)
Javascript:
videojs('vid2', { "techOrder": ["vimeo"], "src": "https://vimeo.com/63186969" }).ready(function() {
// You can use the video.js events even though we use the vimeo controls
// As you can see here, we change the background to red when the video is paused and set it back when unpaused
this.on('pause', function() {
document.body.style.backgroundColor = 'red';
});
this.on('play', function() {
document.body.style.backgroundColor = '';
});
// You can also change the video when you want
// Here we cue a second video once the first is done
this.one('ended', function() {
this.src('http://vimeo.com/79380715');
this.play();
});
myPlayer.src("http://video-js.zencoder.com/oceans-clip.mp4");
var myPlayer = videojs('vid2');
myPlayer.ready(function(){ /*Video is ready*/ });
myPlayer.error(function(){ /*An error happened*/ });
mpPlayer.play();
]);
So there are the 2 events:
var myPlayer = videojs('example_video_1');
myPlayer.ready(function(){ /*Video is ready*/ });
myPlayer.error(function(){ /*An error happened*/ });
More api info here : https://github.com/videojs/video.js/blob/master/docs/api/vjs.Player.md

Detect if HTML5 Video element is playing [duplicate]

This question already has answers here:
How to tell if a <video> element is currently playing?
(7 answers)
Closed 1 year ago.
I've looked through a couple of questions to find out if an HTML5 element is playing, but can't find the answer. I've looked at the W3 documentation and it has an event named "playing" but I can't seem to get it to work.
This is my current code:
var stream = document.getElementsByTagName('video');
function pauseStream() {
if (stream.playing) {
for (var i = 0; i < stream.length; i++) {
stream[i].pause();
$("body > header").addClass("paused_note");
$(".paused_note").text("Stream Paused");
$('.paused_note').css("opacity", "1");
}
}
}
It seems to me like you could just check for !stream.paused.
Check my answer at How to tell if a <video> element is currently playing?: MediaElement does not have a property that tells if it is playing or not. But you could define a custom property for it.
Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
get: function(){
return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
}
})
Now you can use it on video or audio elements like this:
if(document.querySelector('video').playing){
// Do anything you want to
}
Note : This answer was given in 2011. Please check the updated documentation on HTML5 video before proceeding.
If you just want to know whether the video is paused, use the flag stream.paused.
There is no property for a video element in getting its playing status. But there is one event "playing" which will be triggered when it starts to play. An Event called "ended" is also triggered when it stops playing.
So the solution is:
Declare one variable videoStatus.
Add event handlers for different events of video.
Update videoStatus using the event handlers.
Use videoStatus to identify the status of the video.
This page will give you a better idea about video events. Play the video on this page and see how the events are triggered.
http://www.w3.org/2010/05/video/mediaevents.html
jQuery(document).on('click', 'video', function(){
if (this.paused) {
this.play();
} else {
this.pause();
}
});
Add eventlisteners to your media element. Possible events that can be triggered are: Audio and video media events
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Html5 media events</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body >
<div id="output"></div>
<video id="myVideo" width="320" height="176" controls autoplay>
<source src="http://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">
<source src="http://www.w3schools.com/tags/mov_bbb.ogg" type="video/ogg">
</video>
<script>
var media = document.getElementById('myVideo');
// Playing event
media.addEventListener("playing", function() {
$("#output").html("Playing event triggered");
});
// Pause event
media.addEventListener("pause", function() {
$("#output").html("Pause event triggered");
});
// Seeking event
media.addEventListener("seeking", function() {
$("#output").html("Seeking event triggered");
});
// Volume changed event
media.addEventListener("volumechange", function(e) {
$("#output").html("Volumechange event triggered");
});
</script>
</body>
</html>
Best approach:
function playPauseThisVideo(this_video_id) {
var this_video = document.getElementById(this_video_id);
if (this_video.paused) {
console.log("VIDEO IS PAUSED");
} else {
console.log("VIDEO IS PLAYING");
}
}
I encountered a similar problem where I was not able to add event listeners to the player until after it had already started playing, so #Diode's method unfortunately would not work. My solution was check if the player's "paused" property was set to true or not. This works because "paused" is set to true even before the video ever starts playing and after it ends, not just when a user has clicked "pause".
You can use 'playing' event listener =>
const video = document.querySelector('#myVideo');
video.addEventListener("playing", function () {
// Write Your Code
});
Here is what we are using at http://www.develop.com/webcasts to keep people from accidentally leaving the page while a video is playing or paused.
$(document).ready(function() {
var video = $("video#webcast_video");
if (video.length <= 0) {
return;
}
window.onbeforeunload = function () {
var htmlVideo = video[0];
if (htmlVideo.currentTime < 0.01 || htmlVideo.ended) {
return null;
}
return "Leaving this page will stop your video.";
};
}
a bit example
var audio = new Audio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')
if (audio.paused) {
audio.play()
} else {
audio.pause()
}
I just looked at the link #tracevipin added (http://www.w3.org/2010/05/video/mediaevents.html), and I saw a property named "paused".
I have ust tested it and it works just fine.
This is my code - by calling the function play() the video plays or pauses and the button image is changed.
By calling the function volume() the volume is turned on/off and the button image also changes.
function play() {
var video = document.getElementById('slidevideo');
if (video.paused) {
video.play()
play_img.src = 'img/pause.png';
}
else {
video.pause()
play_img.src = 'img/play.png';
}
}
function volume() {
var video = document.getElementById('slidevideo');
var img = document.getElementById('volume_img');
if (video.volume > 0) {
video.volume = 0
volume_img.src = 'img/volume_off.png';
}
else {
video.volume = 1
volume_img.src = 'img/volume_on.png';
}
}
I just did it very simply using onpause and onplay properties of the html video tag. Create some javascript function to toggle a global variable so that the page knows the status of the video for other functions.
Javascript below:
// onPause function
function videoPause() {
videoPlaying = 0;
}
// onPause function
function videoPlay() {
videoPlaying = 1;
}
Html video tag:
<video id="mainVideo" width="660" controls onplay="videoPlay();" onpause="videoPause();" >
<source src="video/myvideo.mp4" type="video/mp4">
</video>
than you can use onclick javascript to do something depending on the status variable in this case videoPlaying.
hope this helps...
My requirement was to click on the video and pause if it was playing or play if it was paused. This worked for me.
<video id="myVideo" #elem width="320" height="176" autoplay (click)="playIfPaused(elem)">
<source src="your source" type="video/mp4">
</video>
inside app.component.ts
playIfPaused(file){
file.paused ? file.play(): file.pause();
}
var video_switch = 0;
function play() {
var media = document.getElementById('video');
if (video_switch == 0)
{
media.play();
video_switch = 1;
}
else if (video_switch == 1)
{
media.pause();
video_switch = 0;
}
}
I just added that to the media object manually
let media = document.querySelector('.my-video');
media.isplaying = false;
...
if(media.isplaying) //do something
Then just toggle it when i hit play or pause.
a bit example when playing video
let v = document.getElementById('video-plan');
v.onplay = function() {
console.log('Start video')
};

Categories