HTML5 video - Play event not firing - javascript

I currently have an HTML5 video event issue in Safari. I am playing a single video on my page. The video loads and plays correctly. However, the play event does not always fire. If the user:
Clicks play
Watches the video to the end (ended event fires)
Clicks play again
The play event does not fire on the second click. If I pause/play the movie at that time, the correct events fire.
How can I make the video tag's play event fire if the video has completed and the user presses play again?
drawVidPlayer is called with the videos index as part of the page render
function drawVidPlayer(vindex){
var turl=vidList[vindex]['thumbUrl'];
var vurl=vidList[vindex]['url'];
var valias=vidList[vindex]['type'];
destroyVidPlayer();
$('#mediaspot').css('backgroundColor', '#000000');
$('#mediaspot').show();
$('#mediaspot').html('<video controls="controls" id="twnvideo" poster="'+turl+'" style="height:225px; width:460px;"><source src="'+vurl+'" type="video/ogg" /><source src="'+vurl+'" type="video/mp4" /><source src="'+vurl+'" type="video/webm" />Your browser does not support the video tag.</video>').appendTo('#wrap_media_vod');
var velem=document.getElementsByTagName('video')[0];
velem.addEventListener('play', initVidTimer, false);
velem.addEventListener('pause', killVidTimer, false);
velem.addEventListener('ended', killVidTimer, false);
}
function destroyVidPlayer(){
var velem=document.getElementsByTagName('video')[0];
if(velem!=undefined){
velem.removeEventListener('play', initVidTimer);
velem.removeEventListener('pause', killVidTimer);
velem.removeEventListener('ended', killVidTimer);
}
$('#mediaspot').empty();
$('#mediaspot').html('');
}
function initVidTimer(){
if(activityTimer==null){
external.OnUserActivity(19);
activityTimer=setInterval(function(){
external.WriteLog('activity timer running');
external.OnUserActivity(19);
}, 5000);
}
}
function killVidTimer(){
clearInterval(activityTimer);
activityTimer=null; // Kill keepAlive timer
var velem=document.getElementsByTagName('video')[0];
external.WriteLog(velem.ended);
}

HTML5 now specifies that the browser must throw the timeupdate, paused, and ended events when the playback position reaches the end of a media file, but the spec wasn't always that clear. As a result, this behavior is inconsistent between browsers. Some don't set paused=true or fire the paused event when the file ends.
In your Safari issue, paused is still equal to false when the video starts to play for the second time - so there is no reason for the browser to fire the play event again.
This may no longer be an issue in Safari 6, but it still breaks in IE 9. Take a look at the End Events column in this chart from longtailvideo.com - they outline the inconsistencies well.
It would easy to normalize this issue with a couple lines of code - like this:
$("video").on("ended", function () {
if (!this.paused) this.pause();
});
This puts the video in the paused state on ended, so it will throw the play event correctly on replay.
You can try this working sample in IE 9 or to see what I mean on this jsfiddle: http://jsfiddle.net/PWnUb/

I had the same issue, I solved with a bit of jquery:
function videoend(){
var duration = $("video").get(0).duration;
var current = $("video").get(0).currentTime;
if(current==duration){
//Whatever you wanna do when video ends
};
}
$(document).ready(function(){
setInterval("videoend()", 200); //or any other time you wanna use
});
Hope this helps.

Related

How to not trigger video ended event when it has EventListener

I have a webpage with three small html5 videos. When this part of the page loads the first video plays, then when it ends the second video plays, and when the second ends then the third plays. I did this with addEventListener for 'ended'. My code looks like this:
//first video
var player1=document.getElementById('firstVideo');
player1.addEventListener('ended',vidHandlerLow,false);
//second video
var player2=document.getElementById('secondVideo');
player2.addEventListener('ended',vidHandlerMedium,false);
//third video
var player3=document.getElementById('thirdVideo');
player3.addEventListener('ended',vidHandlerHigh,false);
player1.play();
function vidHandlerLow() {
player1.pause();
player2.play();
}
function vidHandlerMedium() {
player2.pause();
player3.play();
}
function vidHandlerHigh() {
player3.pause();
}
The issue I'm having is that i'm trying to play a single video on hover without triggering the ended event which will play the rest. I have tried:
onmouseover="this.removeEventListener('ended'); this.play();"
But the ended event is still triggered. If I hover over video1 then video1 will play then two and three when only the hovered video should play. Any suggestions how to play a single video without my video ended events from running?
Since I only need the videos to autoplay once I was able to remove the event listeners in the functions I call on 'ended' like this:
function vidHandlerLow() {
player1.pause();
player1.removeEventListener('ended', vidHandlerLow);
player2.play();
}

HTML5 video won't restart on Mobile Safari

I'm having an issue on Mobile Safari where my HTML5 video won't return to the start once it has finished, so that when it is played again it tries to play the last second before closing once again.
I've attached a handler to the "ended" event so that it closes to the full screen once the video has finished:
$(videoID).bind("ended", function() {
$(videoID).get(0).webkitExitFullScreen();
});
Any ideas?
I should add that I've tried resetting the currentTime to 0, but this doesn't seem to work.
Ended up that I had stupidly put currentTime=0 after exiting full screen when it needed to be before. i.e.
$(videoID).bind("ended", function() {
$(videoID).get(0).currentTime = 0;
$(videoID).get(0).webkitExitFullScreen();
});

Mediaelement.js wont play with Flash-fallback

I'm using Mediaelement.js to play some video and using javascript to get autoplay working. It works perfectly in Chrome, and IE10, but when it comes to Firefox and IE8 I have a problem with the flash fallback. The following works in Chrome:
jQuery('video,audio').mediaelementplayer();
if(autoPlay == "true") {
player = new MediaElementPlayer("#"+currentPage+" video,audio");
player.play();
}
IE8 returns the following:
And firefox returns no errors, but if I add an alert(alert("hallo");) in front of player.play(), it plays when I dismiss the alert-box.
I can't add fiddle, because of heavy use of XML.
The player isn't loaded up and ready to play when the script presses the play button.
The script needs to press the play button inside the success function in the mediaelement instance creation.
See here: How do I get mediaelement.js player state (paused, volume, etc.)?
Some browsers (webkit specifically) may trigger the play() method before the video is completely ready and the video may just hang while loading.
I would advice to add an event listener to detect when the video can actually play before triggering the play() method like :
success : function (media, domObject) {
media.addEventListener('canplay', function () {
media.play();
}, false);
} // success
Yeah sorry, solved it a half year later:
As mentioned, the play event must be invoked in the success function
jQuery("video,audio").mediaelementplayer();
if(autoPlay == "1") {
media = jQuery("#"+currentPage+" video,audio")[0];
new MediaElement(media, {success: function(media) {
media.play();
}});
}

Play (and replay) a sound on safari mobile

I need to play a sound when a new message appears on a website. It works fine on Chrome and Safari but I can't make it work on Safari mobile.
I saw that the sound has to be initialised with a user action so I tried that:
var sound = new Audio('./path/to/my/sound.mp3');
var hasPlayed = false;
$('body').bind('click touchstart', function() {
sound.load();
});
sound.addEventListener('play', function() {
hasPlayed = true;
});
var playSound = function() {
if(hasPlayed) {
sound.currentTime = 0;
}
sound.play();
}
Unfortunately, the sound still don't play. I also tried with the Buzz library, and the issue is the same.
So, the question is : how can I play a sound programmatically on mobile browsers ?
First of all: HTML5 audio support in Mobile Safari on iOS (5.01, 5.1) is rather limited. But I have managed to get some small 'event type' sounds working in my iPad 2 web apps. Since you are talking about only one sound file for your app, you don't have to fall back on audio sprites tricks (i.e. merging multiple MP3's into one MP3 file and changing the play position within the merged file depending on the sound you want to be played).
As you have noticed, you cannot play audio automatically in Mobile Safari, i.e. without the user clicking on some element. Technically speaking, the audio must be played (not loaded) in the same call stack as a click event. But you will probably experience a 0,5 second delay then, when Mobile Safari creates the audio object. Here is a solution to this 'problem':
At the start of your app (while loading/initializing), add a click handler to the HTML document that starts playing your audio file as soon as the user clicks/taps anywhere in the app. This will force Safari to start loading the audio.
Listen for the 'play' event that is triggered when the audio is ready to be played, and immediately pause.
Now start playing the audio (without delay) again when you need it.
Here is some quick JavaScript code:
function initAudio() {
var audio = new Audio('./path/to/my/sound.mp3');
audio.addEventListener('play', function () {
// When the audio is ready to play, immediately pause.
audio.pause();
audio.removeEventListener('play', arguments.callee, false);
}, false);
document.addEventListener('click', function () {
// Start playing audio when the user clicks anywhere on the page,
// to force Mobile Safari to load the audio.
document.removeEventListener('click', arguments.callee, false);
audio.play();
}, false);
}
For those that are coming across this problem and the solution by Jeroen is not working here is a solution that works and ensures the proper scoping is correctly enforced.
Make sure initAudio is called on page load. I.e. in your Init function or for jquery inside the document.ready ($(function(){});)
function initAudio(){
var audio = new Audio('./path/to/my/sound.mp3');
var self = this;
//not sure if you need this, but it's better to be safe
self.audio = audio;
var startAudio = function(){
self.audio.play();
document.removeEventListener("touchstart", self.startAudio, false);
}
self.startAudio = startAudio;
var pauseAudio = function(){
self.audio.pause();
self.audio.removeEventListener("play", self.pauseAudio, false);
}
self.pauseAudio = pauseAudio;
document.addEventListener("touchstart", self.startAudio, false);
self.audio.addEventListener("play", self.pauseAudio, false);
}

How to lock controls on <video> in HTML5 till a given event happens?

I want to pause the video being played at a particular instant till a question that pops up has been answered. The user should not be able to go ahead and forward the video till a particular question that has just poppped up has been answered.
So I can pause the video using JS at that particular instant. How can I ensure the video's controls are unlocked or the video plays again only after answering the question that pops up?
look at this demo http://jsfiddle.net/dgLds/58/
var video = document.getElementById("myvideo");
function toggleControls() {
document.getElementById('myvideo').pause();
if (video.hasAttribute("controls")) {
video.removeAttribute("controls")
} else {
video.setAttribute("controls","controls")
}
}
<video id="myvideo">
<source src="http://www.w3schools.com/html5/movie.mp4" />
</video>
<p onclick="toggleControls();">Toggle</p>
instead of on click you can call the function when ever you want
Here is a opera article on everything you wish to know about html5 video http://dev.opera.com/articles/view/everything-you-need-to-know-about-html5-video-and-audio/
Specifically look at How to keep things synchronized section
EDIT: I you want to disable right-click options. Just go ahead and disable right click on that tag/id
Here is a jquery code
$('video').bind('contextmenu', function()
{
alert('no right click.');
return false;
});
I ran into the need to be able to disable the context menu myself today because we have our own custom controls. You can do this fairly easily:
video.addEventListener('contextmenu', function(e) {
e.preventDefault();
return false;
});
He is an example built upon Web Developer's demo: http://jsfiddle.net/dgLds/308/
There is a pause() method available for the video element:
document.getElementById('myVideo').pause();
Similarly, there is play().

Categories