Mobile Safari HTML5 video - event listener 'ended' does not fire the 2nd time
I am trying to add a button when pressed will play a video, and when the video ends an image is displayed. The problem is that the 2nd time i press the button, the video ends, and nothing happens as if the event listener does not get called.
var video = document.getElem开发者_开发技巧entById("video");
function playVideo() {
video.style.display="block";
//video.load() [adding this the 2nd time wont play]
video.play();
video.addEventListener('ended', videoEnd, false);
}
function videoEnd() {
video.style.display="none";
bg_image.src="image.jpg";
}
This is due to a strange bug in Safari's HTML5 video tag implementation. It can be reproduced on Safari for Windows as well. I've just found one workaround for this problem - just bind to loadedmetadata
event and set the currentTime
to some non-zero value. Here is an example:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
</head>
<body>
<video id="video" width="500" height="400" controls autoplay></video>
<script>
var src = [
"http://content.adfox.ru/131007/adfox/205544/865991_11.mp4",
"http://all.rutube.ru/130627/gpmdigital/217059/805529_11.mp4"
];
var curSrc = 0;
$(function() {
$('#video').attr("src", src[curSrc % src.length]);
curSrc++;
var video = $('#video').get(0);
$('#video')
.on('loadedmetadata', function() {
video.currentTime=0.01;
video.play();
})
.on('ended', function() {
console.log('ended');
video.src = src[curSrc % src.length];
video.load();
curSrc++;
});
});
</script>
</body>
</html>
You can try this demo in this jsfiddle: http://jsfiddle.net/j2knz6sv/
I believe that the "ended" event no longer fires when a VIDEO element reaches the end. Apparently only the "pause" event fires.
I've gotten around this by simply listening to the "timeupdate" event and associating a handler method that checks if the currentTime property is equivalent to the duration property of the VIDEO element.
UPDATE: I sometimes see the "ended" event in iOS. I always see the "pause" event. Here's some jQuery code that displays this information in the browser console:
(function ($) {
$("#vid").bind("timeupdate", function (e) {
console.log(e.type + " - " + (this.currentTime == this.duration));
});
})(jQuery);
You should use timeupdate like this:
this.currentTime >= (this.duration-1)
Otherwise, it doesn't fire an event.
精彩评论