I am building a player logic that loads a movie, plays it to the end, reacts to the "ended" event and sets a new source, that has to be looped until the user interacts. Then, film2 gets played and "switches into loop" as well so i'm loading another src and setting options to loop for the loop.
I just couldn't get it to work.
Here is my code:
<video id="video_1" preload="auto" width="100%" height="100%">
<source src="video/dummy/dummy_film1.mp4" type='video/mp4'>
</video>
And here is my js:
function initialVideoFinished(){
_myPlayer.off('ended', initialVideoFinished);
console.log('video1 finished - video js READY');
console.log('myPlayer id == ' + _myPlayer);
_V_('video_1', {'loop' : 'true'});
_myPlayer.src('video/dummy/dummy_loop1.mp4');
_myPlayer.play();
ni_resize();
}
I tried a lot of variations. Loop in "" or without or _myPlayer.loop = true; V(...) oder just videojs(..) but the new video src never loops.
I also tried replacing the whole tag. This works, but then I lose my reference to the player object.
How can I do this?
You can use loop(true):
var myPlayer = videojs("my_video_1");
function initialVideoFinished(event) {
console.log("end");
myPlayer.off('ended', initialVideoFinished);
myPlayer.src("http://example.com/newsource.mp4");
myPlayer.loop(true);
myPlayer.play();
}
myPlayer.on('ended', initialVideoFinished);
Related
I have video and text that I am displaying when user clicks play button (4 seconds). So my code looks like this:
$('video').on('play', function (e) {
$('#showText').delay(4000).show(0);
});
What I am trying to achieve is hide this text (#showText) 5 seconds before the end of the video. I didn’t find any solution for this, so if anybody can help with this I’ll be more than thankful.
To make this work you can use the standard events associated with media elements. Specifically play and timeupdate. The former you've already covered. The latter fires as the playback progresses. You can use it to check the current position and determine if it's less than 5 seconds from the end, like this:
var $showText = $('#showText');
$('video').on({
play: function() {
$showText.delay(4000).show(0);
},
timeupdate: function(e) {
if ((this.duration - this.currentTime) < 5 && $showText.is(':visible'))
$showText.hide();
}
});
#showText {
display: none;
}
video {
height: 175px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="showText">Lorem ipsum</p>
<video autobuffer controls autoplay>
<source id="mp4" src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">
</video>
You can use video.js to get length of video then you can hide any element at any second before video is ending
var myPlayer = videojs('example_video_1'); //defining videojs
<video id="example_video_1" data-setup="{}" controls="">
<source src="my-source.mp4" type="video/mp4">
</video> //end defining videojs
$('#showText').delay(4000).show(0);
var lengthOfVideo = myPlayer.duration(); // length Of Video in seconds
$(#showText).oneTime(lengthOfVideo-5, function() { // 5 second before video ends
$("showText").hide();
});
Everything in my code works. It just doesn't switch to the next song/video after finishing the current one. I have tried adding an onended event handler (in the tag and in JavaScript) but failed. I also tried jQuery but it did't work. For some reasons it doesn't change songs at the end of the song. Instead, it will replay the same song over and over again.
<video id="vid" src="main/" playsinline autoplay loop>
<script>
var video = document.currentScript.parentElement;
video.volume = 0.1;
var lastSong = null;
var selection = null;
var playlist = ["main/songn.mp4", "main/songl.mp4", "/main/songt.mp4", "/main/songf.mp4"]; // List of Songs
var video = document.getElementById("vid");
video.autoplay=true;
video.addEventListener("ended", selectRandom);
function selectRandom(){
while(selection == lastSong){
selection = Math.floor(Math.random() * playlist.length);
}
lastSong = selection;
video.src = playlist[selection];
}
selectRandom();
video.play();
</script>
</video>
You just need to remove the loop parameter from the video tag if you want to trigger the end event (doc):
<video id="vid" src="main/" playsinline autoplay>
(Your code will handle the loop by loading a new song when one ended.)
BTW, keep var video = document.getElementById("vid"); to refer to your <video> tag, it's shorter and cleaner than the first declaration.
The question of how can JavaScript call the next video has been asked as I have thoroughly researched this topic before posting. However, in the situation that I will describe, a video is running after an onclick event calls the function: function(e) and I need to be able to call the next video by calling the function(e) again once the code detects an ended event by using the addEventListener method.
I have posted all my code below. In addition I have added comments to illustrate what I “think” is happening. I am brand new to JavaScript and have recently retired, so I have had time to research the Internet to try and piece together what is taking place. Please feel free to clarify my commented code as I would appreciate being set straight on what I have wriiten.
I have also made an attempt to put the code on jsfiddle
https://jsfiddle.net/dan2004/tuouh36d/
but it only seems to function in Chrome.
My main question to everyone is in regard to the statement:
document.getElementById('videoPlayer').addEventListener('ended',handler,false);
If I call a function outside of the function, I can issue a message via an alert, but if I call the function that I am in (handler(e)) I cannot get the next video to run. Somehow I need to be able to call the handler(e) function and send it the next onclick event.
Thanks for any help.
var video_playlist, links, i, videotarget, filename, video, source;
// Gets the video object from <div id="player"> in the HTML
video_playlist = document.getElementById("player");
// "links" is an array which contains all the <a href> tags in the <div id="playlist">.
// This div is located within <div id="player"> and contains a clickable playlist.
links = video_playlist.getElementsByTagName('a');
// This "for loop" scrolls through the links array of <a href> attributes and
// assigns an "onclick = handler" event to each one.
for (i=0; i<links.length; i++) {
links[i].onclick = handler;
};
// e is an [object MouseEvent]
function handler(e) {
// The handler function receives the full path to the mp4 file when it is clicked on in the playlist.
// The "preventDefault" method stops the function from following that path.
// This is so the data in the path may be parsed and manipulated below
e.preventDefault();
// videotarget grabs the href attribute of the item clicked on
// in the "playlist". This is the full path to the video file.
videotarget = this.getAttribute("href");
// Through the use of substr, filename grabs that part of the href which
// does not include the extension.
filename = videotarget.substr(0, videotarget.lastIndexOf('.')) || videotarget;
// The variable "video" contains the video object. This is obtained by using document.querySelector().
// This document method uses the css id class, #player, and grabs the [object HTML VideoElement].
// The [object HTML VideoElement] resides in <div id="player">
video = document.querySelector("#player video");
//Removes the poster attribute in the video tag
video.removeAttribute("poster");
// The source variable is used to hold an array of all the source tags in the
// [object HTML VideoElement] from <div id="player">.
source = document.querySelectorAll("#player video source");
// Using the substring extracted from the user's click choice in <div id="playlist">
// the three file types for browsers to choose from are concatenated to the string.
// These thre source files are then stored under the video object located in <div id="player">.
source[0].src = filename + ".mp4";
source[1].src = filename + ".webm";
source[2].src = filename + ".ogv";
// The video object will load the appropriate source[].src file then play it
video.load();
video.play();
// When the video ends the following statement will call the function test()
// which will then broadcast the alert message "Video Ended"
document.getElementById('videoPlayer').addEventListener('ended',test,false);
// This statement will not call the handler function in order to play the next video selection.
// document.getElementById('videoPlayer').addEventListener('ended',handler,false);
}; // function handler(e)
function test(){
alert("Video Ended");
};
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Video Playlist Tutorial</title>
<style>
body {font-family:Arial, Helvetica, sans-serif;background:#fff}
.center {text-align:center;width:640px;margin:0 auto;}
#player {background:#000; padding:10px;width:640px;margin:0 auto;border-radius:10px;}
#player video {width:640px;}
#playlist {background:#333;list-style:none;padding:0;margin:0; width:640px;}
#playlist h1 {font: 24px Arial, Helvetica, sans-serif; color:#FFF; font-weight:bold;padding:5px 2px;margin:0;}
#playlist a {color:#eeeedd;background:#333;padding:10px 5px;display:block;text-decoration:none;border-bottom:1px solid #222;}
#playlist a:hover {text-decoration:none; background:#999;color:#000}
</style>
</head>
<body>
<div id="player"> <!-- Assign id to video tag for ended event and to call handler to play next video -->
<video id="videoPlayer" controls="controls" width="640" height="360" preload="auto" autoplay >
<source src="1.mp4" type="video/mp4" />
<source src="1.webm" type="video/webm" />
<source src="1.ogv" type="video/ogg" />
</video>
<div id="playlist">
<h1>Videos</h1>
Bear <br>
Buck Bunny
</div>
</div>
<script>
</script>
</body>
</html>
Seeing as your handler() function relies on this being the clicked element, you can't just call that function, you'd have to also set the this-value to the next anchor etc. and trigger the event in a way that makes it look like it was triggered by the actual element.
An easier way to do this, would be to just decouple the playing logic, get the next element, and play the video
var video_playlist = document.getElementById("player");
var links = video_playlist.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
(function(j) {
links[j].addEventListener('click', function(e) {
handler.apply(this, [e, j])
});
})(i);
};
function handler(e, index) {
e.preventDefault();
var videotarget = this.getAttribute("href");
play(videotarget, index).addEventListener('ended', function() {
index = (++index) >= links.length ? 0 : index;
play(links[index].getAttribute("href"), index);
});
};
function play(videotarget) {
var filename = videotarget.substr(0, videotarget.lastIndexOf('.')) || videotarget;
var video = document.querySelector("#player video");
var source = document.querySelectorAll("#player video source");
video.removeAttribute("poster");
source[0].src = filename + ".mp4";
source[1].src = filename + ".webm";
source[2].src = filename + ".ogv";
video.load();
video.play();
return video;
};
<div id="player">
<!-- Assign id to video tag for ended event and to call handler to play next video -->
<video id="videoPlayer" controls="controls" width="640" height="360" preload="auto" autoplay>
<source src="1.mp4" type="video/mp4" />
<source src="1.webm" type="video/webm" />
<source src="1.ogv" type="video/ogg" />
</video>
<div id="playlist">
<h1>Videos</h1>
Bear
Buck Bunny
</div>
</div>
I'm just trying to work on my javascript skills and I am trying to make a page that will load up an HTML5 video at random from an array.
Once the video is loaded I am trying to set it so once the video is clicked it will trigger the function to randomize a new video from the array and output the result into the HTML video code.
So every time the user clicks a video will be randomized and begin playing on the page.
I believe I am pretty close with the code I have written so far, but I can't seem to get it to randomize after it clicked on every click.
Here is my code
HTML
<a href="#" class="click">
<section>
<div>
<video loop autoplay>
<source src="videos/1.mpg" type="video/ogg">
<source src="videos/1.webm" type="video/mp4">
Your browser does not support the <code>video</code> element.
</video>
</div>
</section>
</a>
JavaScript
// Loads in Notifier
$(document).ready(function(){
swal({ title: "Tap or Swipe to randomize",
confirmButtonColor: "#FF1D23",
confirmButtonText: "Cool!",
imageUrl: "images/thumbs-up.jpg",
timer: 4000
});
});
//Array of Videos
var videos = [
[{type:'mp4', 'src':'videos/1.mp4'}, {type:'webm', 'src':'videos/1.webm'}],
[{type:'mp4', 'src':'videos/2.mp4'}, {type:'webm', 'src':'videos/2.webm'}],
];
//onClick + Action
$(function() {
$('a.click').click(function(e) {
e.preventDefault();
var randomIndex = parseInt(Math.random()*videos.length);
$(this).find('videos').append('<source src="'+videos[randomIndex]+'" />');
});
});
function getRandomVideo() {
var number = Math.floor(Math.random()*video.length);
document.write('<source src="'+videos[number]+'" />');
}
$(function() {
$('a.click').click(function(e) {
e.preventDefault();
console.log("hello world");
var number = Math.floor(Math.random()*videos.length);
$(this).html('<source src="'+videos[number]+'" />');
});
});
See this fiddle
//onClick + Action
$('a.click').click(function(e) {
e.preventDefault();
var randomIndex = parseInt(Math.random()*videos.length);
$(e.currentTarget).find('video').html('<source src="'+videos[randomIndex][0].src+'" type="video/ogg" /><source src="'+videos[randomIndex][1].src+'" type="video/mp4" />');
});
I left your data structure alone, although it could be structured better.
Couple of issues. First, you aren't creating your HTML string correctly. You have to use videos[randomIndex][0].src (notice the src). Secondly, you are .append() when you should be .html(). And lastly, you .find('videos') instead of .find('video'). The tag is a video (no S).
EDIT:
Also, you can't do $(this).find(...) in that context. this refers to the click event, not the a tag. You need to get the TARGET of the event $(e.currentTarget).find('video'), not the event.
videos[number][0].src for .mp4 format
and
videos[number][1].src for .webm format
and make sure to correct object declaration:
{type:'mp4', 'src':'videos/2.mp4'}
should be {type:'mp4', src:'videos/2.mp4'}
I'm having trouble getting HTML5 audio to loop on my website: http://oclock.webs.com.
(It's an alarm which, when the alarm goes off, is supposed to loop a 1 second alarm sound over and over until you click OK on the alert box).
Simply including "loop" in the audio tag wasn't doing anything.
I found a helpful post on StackOverflow which lead me to this website: http://forestmist.org/2010/04/html5-audio-loops/
I knew Method 1 and 2 wouldn't work for me since they don't work on Firefox and are iffy on Chrome, and so Method 3 should have worked, unfortunately it didn't. Method 3 works when I'm on that website's page, but not when the code is included in my own page so I think there may be some conflicting code.
Relevant part of my webpage:
<audio id="audio1" preload>
<source src="media/alarm.ogg" type="audio/ogg" />
<source src="media/alarm.mp3" type="audio/mpeg" />
</audio>
<audio id="audio2" preload>
<source src="media/alarm.ogg" type="audio/ogg" />
<source src="media/alarm.mp3" type="audio/mpeg" />
</audio>
Relevant Javascript of the page:
if(timer==true && hours==hv && mins==mv && secs==sv){
document.getElementById("audio1").play();
alert("o'clock: Alarm ringing!");
document.getElementById("alarm").value="Set Alarm";
document.getElementById('audio1').addEventListener('ended', function(){
this.currentTime = 0;
this.pause();
document.getElementById('audio2').play();
}, false);
document.getElementById('audio2').addEventListener('ended', function(){
this.currentTime = 0;
this.pause();
document.getElementById('audio1').play();
}, false);
}
else{
document.getElementById("audio1").pause();
document.getElementById("audio2").pause();
document.getElementById("audio1").currentTime = 0;
document.getElementById("audio2").currentTime = 0;
}
Intention: Upon the computer's time matching that of the selected time on the page, the audio alarm will repeat (loop) until the user clicks OK on the alert box popup.
Problem: Currently it only plays through the audio once, it doesn't loop. Where did I mess up?
"ended event" or "loop" property dose not work on some browsers.
So I used window.setInterval() for looping audio playing.
For this method, you should know play time of Audio file in advanced.
function playAudioWithLoop (/**HTMLAudioElement*/audio, /**Number*/length)
{
function onEnd (){
audio.play();
}
/* length is msec */
if(length > 0) {
audio.__timer = window.setInterval(onEnd, length);
}
}
function stopAudioWithLoop (/**HTMLAudioElement*/audio)
{
if(audio.__timer) {
audio.__timer = window.clearInterval(audio.__timer);
}
}
======================================================================
***playAudioWithLoop(document.getElementById("audio1"), 12*1000);***
***stopAudioWithLoop(document.getElementById("audio1"));***