Start HTML5 video at a particular position when loading? - javascript

I need HTML5 video to start at certain point. Let's say at time 50 seconds onward.
I tried but its not working as expected. is there something i am doing wrong?
Here is the code:
<video id="vid1" width="640" height="360">
<source src="file.webm" type="video/webm" />
Your browser does not support the video tag.
</video>
<script>
document.getElementById('vid1').currentTime = 50;
</script>
When the page loads, it just starts playing from beginning.
However if I call this during playback like after some time, it works fine.
Is there anything I am missing?

You have to wait until the browser knows the duration of the video before you can seek to a particular time. So, I think you want to wait for the 'loadedmetadata' event something like this:
document.getElementById('vid1').addEventListener('loadedmetadata', function() {
this.currentTime = 50;
}, false);

WITHOUT USING JAVASCRIPT
Just add #t=[(start_time), (end_time)] to the end of your media URL. The only setback (if you want to see it that way) is you'll need to know how long your video is to indicate the end time.
Example:
<video>
<source src="splash.mp4#t=10,20" type="video/mp4">
</video>
Notes: Not supported in IE

You can link directly with Media Fragments URI, just change the filename to file.webm#t=50
Here's an example
This is pretty cool, you can do all sorts of things. But I don't know the current state of browser support.

adjust video start and end time when using the video tag in html5;
http://www.yoursite.com/yourfolder/yourfile.mp4#t=5,15
where left of comma is start time in seconds, right of comma is end time in seconds.
drop the comma and end time to effect the start time only.

On Safari Mac for an HLS source, I needed to use the loadeddata event instead of the metadata event.

Related

How to make users STOP the execution of an HTML5 audio autoplay file clicking anything on the page?

I'm working on a page that, on my client's request, loads playing a background soundtrack.
Of course it's just for those users who are not navigating with audio autoplay disabled.
So the simple piece of code used to start playing the music is something like the following:
<audio autoplay id="background-soundtrack">
<source src="mytrack.mp3" type="audio/mpeg">
</audio>
I'd like to make music stop (even better: make it fade out in a matter of a few seconds) as soon as the user clicks anywhere on the page -- it should work tapping on mobile devices too.
Can you please suggesitng me a smart way to achieve my goal?
It doesn't matter if it's pure JavaScript or jQuery.
Thanks!
try this jquery:
$('document').on('click','body',function(){
if ($('#background-soundtrack').paused == false){
$('#background-soundtrack').animate({volume: 0}, 1500,
//1500 duration time
function(){
$('#background-soundtrack').pause()
});
}
});
The HTML5 audio elements has the pause method, that you can use at "onClick" (work in touch too) event on body, document, window...
Like this (I delete the "-" in id):
document.onclick = function(e){
backgroundsoundtrack.pause();
}
<audio autoplay id="backgroundsoundtrack">
<source src="mytrack.mp3" type="audio/mpeg">
</audio>

How to change current time of a paused html5 video and start playing from that position?

I have a html 5 video on a page like this:
<video preload="none" id="movie" poster="http://my_poster_url.com/sourcefile.jpeg" controls>
<source id="mp4" type="video/mp4" src="http://my_mp4.com/sourcefile.mp4"></source>
<source id="webm" type="video/webm" src="http://my_webm.com/sourcefile.webm"></source>
</video>
Below that video I have a navigation where you can skip to different times in the video. It works perfectly when the video is playing, but when paused following error occurs:
InvalidStateError: An attempt was made to use an object that is not,
or is no longer, usable
Here the function:
$('#my_video_navigation a').click(function () {
var start_in_seconds=...//a variable that gets the time from a json based on the navigation index
$("#movie").get(0).currentTime = start_in_seconds;
$("#movie").get(0).play();
}
I added an if/else statement wether the video is paused or not:
if ($('#movie').get(0).paused) {
$("#movie").get(0).play();
}
and then tried to set the current time like above and even with a set timeout function so that it will wait till the video loaded and is playing but that didn't work. What am I doing wrong or what did I forget?
You should change the currentTime field of the media element, as you can see here in the API doc. There is also an example code here, at MDN
For reference, the sample code there:
var mediaElement = document.getElementById('mediaElementID');
mediaElement.seekable.start(); // Returns the starting time (in seconds)
mediaElement.seekable.end(); // Returns the ending time (in seconds)
mediaElement.currentTime = 122; // Seek to 122 seconds
mediaElement.played.end(); // Returns the number of seconds the browser has played
where the mediaElementID is the id of the audio or video tag.
Edit: It seems I've misread your question. I will take a further look.

How to force a html5 video to load fully?

I have a few html5 videos on a page. When I first enter the page, they load correctly - I can see the correct frame size, play the video etc. etc. After going to another page and coming back to the video page the frames are not high enough and the video doesn't play, doesn't go fullscreen etc.
In my opinion it's something with video loading. I tried using onloadeddata without success (I might have used it wrong though, newbie here).
Is there any way the video can be forced to load? Like a loop checking if the videos are loaded, if not - loading them?
UPDATE: Here's the code.
var content = '';
var index;
$.post('api/getVideo.php', {id: id}, function(data) {
//console.log(data);
for (index = 0; index < data.length; index++) {
content = content + '<div class="col-md-6 video-col"> <button id="play" class="full-play-button"><i class="fa fa-play"></i></button>' +
'<video id="video1" class="video-small"> <source src="'+data[index]["Path"] + '"type="video/'+data[index]["Typ"]+'" class="video-file"> </video><h3 class="video-title">'+
data[index]["Tytul"]+'</h3></div>';
}
}, "json");
You might have a typo in your source tag. Try changing '"type="video/' to '"type=video/"'. Modern browsers don't require the type attribute, anymore, so try removing '"type="video/'+data[index]["Typ"]+' completely. I don't have enough info to test your code, but it looks like a syntax error.
From MediaAPI docs,
The Media API also contains a load() method which: "Causes the element to reset and start selecting and loading a new media resource from scratch." (
Load element causes browser to run media element load algorithm)
You can trigger load while returning back from the new page.
In short this is not fully possible. For short videos you can set the preload attribute to "auto" or the empty string "". This means, that you want the browser to preload the source entirly.
Unfortunatley, in case of long videos, the video isn't fully downloaded by most browsers. In case of mobile browser explicitly iOS. The preload attribute doesn't work. So the way to this look like this:
<video preload="" controls="">
<source src="my-video.mp4" type="video/mp4" />
<source src="my-video.webm" type="video/webm" />
</video>

HTML5 Video Seamless Looping

I know this question has been asked a number of times, and I've looked through every single one of them here on StackOverflow.
I'm simply trying to loop a 5 second MP4 video in an HTML5 player and have it be seamless. I've tried both jwplayer and video.js, both locally and on webspace, and neither do the trick. I've tried using the "ended" events; I've tried preloading/prebuffering; I've tried listening for the final second of a video and then seeking to the beginning to bypass the stop/play events entirely. I still always see jitter, and I still always see the loading icon (latest Chrome & Firefox).
For reference, here's some of my latest code for video.js:
<video id="loop_me" class="video-js vjs-default-skin vjs-big-play-centered"
width="640" height="480"
data-setup='{"controls": false, "autoplay": true, "loop": true, "preload": "auto"}'>
<source src="video/loop_me.mp4" type="video/mp4" />
</video>
<script type="text/javascript">
var myPlayer = videojs("loop_me");
videojs("loop_me").ready(function(){
this.on("timeupdate", function(){
var whereYouAt = myPlayer.currentTime();
if (whereYouAt > 4) {
myPlayer.currentTime(1);
}
});
});
</script>
Has anyone managed to do this successfully? And, if so, could you please post a complete solution? I don't normally ask for or want those, but I think it might be necessary this time.
Try this:
1) edit your video this way:
[1s][2s][3s][4s][5s]
cut 1st second block of the video and append it 2x to the end like this:
[2s][3s][4s][5s][1s][1s]
2) Use code:
<video id="vid" width="100" height="50" loop autoplay preload="true">
<source src="something.mp4" type="video/mp4">
</video>
<!-- Goes to end of body of course -->
<script>
var vid = document.getElementById("vid");
vid.addEventListener("timeupdate", function () {
if(this.currentTime >= 5.0) {
this.currentTime = 0.0;
}
});
</script>
The idea behind this is to make the video seamless (the end of the video is the beginning of the video). Also, you have to make sure the video never ends. The loop attribute works with smaller video files but you see a black image at the end of the video if too large (before the next looping iteration). Essentially before the video ends, you are seeking back to 0.0s.
I hope that helps.
Heureka!
We've found the actual, real, work-around-free solution to this problem over at where I work. It explains the inconsistent behavior through multiple developers as well.
The tl;dr version is: Bitrates. Who would've guessed? What I suppose is that many people use standard values for this that usually are around 10 Mbit/s for HD videos if you use the Adobe Media Encoder. This is not sufficient.
The correct value would be 18 Mbit/s or maybe even higher. 16 is still a bit janky.
I cannot express how well this works. I've, by now, tried the messiest workarounds for about five hours until I found this together with our video editor.
I hope this helps everyone and saves you tons of time!
Doozerman and Offbeatmammal are correct: no Javascript is required to loop video in HTML5.
About that pause before each iteration: in some browsers we, too, can observe a pause at the end of the loop in our tests. E.g., in the inline, 22-second demo video at...
http://www.externaldesign.com/Marlin-Ouverson.html
...under OS X, we see a ~0.5 sec. pause before the loop repeats -- only in Firefox and Safari; Chrome and Opera both play the loop without noticeable pause. But note: for desktop/laptop browsers, the above page provides an added full-screen background video that appears to loop without pause in all four of the above browsers.
You don't need any extra scripts for that kind of stuff.
The "video" tag has built in loop attribute, use this and your video will loop.
<video id="loop_me" class="video-js vjs-default-skin vjs-big-play-centered" width="640" height="480" controls autoplay loop>
<source src="video/loop_me.mp4" type="video/mp4" />
</video>
You can also add preload attribute if you wanted to. If you want, you can find more information about the video tag here: HTML video Tag
Edit: Oops. Didn't notice Offbeatmammals comment under your question. :)

How do I play a sound on Image-Click in HTML?

I'm trying to play a sound when i click or hover over my play button? Here's what i have so far. I have a button, if i hover over it it changes the Image, now i also want it to play an mp3.
play a {
position:relative;
float:left;
width:155px;
height:134px;
background-image:url(../images/Goodsound_PLAY_UP.png);
}
play a:hover {
background-image:url(../images/Goodsound_PLAY_P.png);
I want to play a sound here
}
Im sorry for asking such an easy question. I'm an html noob, started last week.
It's not that easy to play a sound in HTML. In fact, it wasn't until the html5 audio was there ! Even if html5 is not supported everywhere, it's now a little bit easier to play a sound in the browser.
My advice is to use mediaelementJS, a javascript library that fills the gap between old browser and html5 audio (and video) spec. Do not use the player (that comes with a full control bar), but use only the mediaelementjs component. To use it, simply include the library in the head of your page
<script src="js/libs/mediaelement.min.js"></script>
First, you have to put an audio tag in your html :
<audio id="mySound" src="my_audio_file.mp3" type="audio/mpeg"></audio>
Then, call the Mediaelement library
var mySound = new MediaElement('mySound');
Finally, play it on your click or over event (here I use jQuery)
$('.play a').mouseover(function(){ mySound.play() });
You can use this:
JavaScript
var audio = $("#audio");
$("play a").mouseenter( function() {
audio.play();
}
where audio is an <audio> element, and play a is element which is hover.
Using jQuery:
$("object_element_id") .on ('mouseover', function(e){
// audio play code here
});
$("object_element_id") .on ('mouseout', function(e){
// audio pause/stop code here
});
Why "on"? Just imagine a "AJAX page refresh". For remove it:
$("object_element_id") .off ('mouseenter');
Why "mouseover" and "mouseout"? Maybe you want to add extra functions for each status, like change IMG SRC of the button, make some effects... feel free. And why the "e" element? The E element is the object who fired the event - the image, the link etc. Do everything with it (or just remove it).
For audio play, you can use HTML5 tags. It's easy and are supported by the major browsers (you didn't asked "retrocompatibility") You can cache the element (like Mateusz' answer) and use it:
var $audio = $("#audio_element_id"); //for cache the element
$audio.setAttribute('src', url_link); //for change the URL file (ir can be MP3, OGG...)
$audio.play(); //for the mouseover
$audio.stop(); //for the mouseout
Then, the final code:
var $audio = $("audio_element"); //caching
$("object_element_id") .on ('mouseover', function(e){
$audio.play();
});
$("object_element_id") .on ('mouseout', function(e){
$audio.stop();
});
You might also find this code useful (I think it is fairly modern, so it might not work with old browsers; I use it with Firefox 32).
<audio controls> <source src="song.mp3" type="audio/mpeg"> </audio>
There is a similar one for video, too:
<video width="320" height="240" controls> <source src="clip.mp4" type="video/mp4"> </video>

Categories