Use YoutubeAPI to play youtube video until a particular time and pause - javascript

Is there a way to use the Youtube API to play a video until a certain point in the video and then pause it?

I've modified the code from the YouTube Player API Reference for iframe Embeds to pause play after a certain number of seconds.
Demo
The code works by waiting for the onPlayerStateChange event. When the event fires, it checks the event to see if it's a PLAYING event. If it is, it calculates the remaining time from the current time (getCurrentTime() method) to the desired pause point (hardcoded as the stopPlayAt variable). It sets a Javascript timer to wait that difference and then pass the API a command to pause the video.

You can use the command cueVideoById in Object syntax to achieve this.
See here: https://developers.google.com/youtube/iframe_api_reference#cueVideoById
This is the way it should look like to start a video like this.
//Minimal Example
player.cueVideoById({videoId:String, endSeconds:Number});
player.playVideo();
EDIT: The above sample stops the video. If you want to pause it, a little more action is required by the JavaScript code.
In detail, you have to poll for the right time.
function checkTime() {
if ( player.getCurrentTime() == finishTime )
player.pauseVideo()
else
setInterval(checkTime, 500);
}
checkTime();
Or keep track of the time in JS:
var duration = finishTime - player.getCurrentTime();
player.playVideo()
setInterval("player.pauseVideo();", duration*1000);

Related

.stop(), and .pause() don't work where .play() does work

On a .js page in a Visual Studio express ASP.NET solution
why does
window.onload() {
document.getElementById('ambience').play();
}
work(and it does!), but why does
window.onload() {
document.getElementById('ambience').play();
document.getElementById('ambience').stop();
}
NOT stop the music? .pause(); doesn't pause the music either
I also tried:
It does play the music. And I have tried:
window.onload = function() {
var snd = document.getElementById('ambience').play();
var clickmeButton = document.getElementById('playJackpot');
clickmeButton.onclick = playSound;
}
function playSound() {
document.getElementById('ambience').stop();
}
what is the equivalent of .stop() or .pause() if those are not applicable? what set of commands
should I be working with in visual studio in order to get sound to play based on a conditional and then definitively shut off or stop after it has played once, and only once ? The background to this is that I have the play button in a timer control, so that it can operate other features, but each timer tick (and that needs to be set at a fraction of a second) kicks off the play again, so that the sound comes out staccato, because it is starting with every 'tick' of the timer. So, I need to play it, then immediately shut off the sound's ability to play, that is until somebody hits the play button again.

Listen for when an HTML5 Audio element stops playing

I need to call a function when an HTML5 audio element stops playing. Specifically the function will reset the seek bar and change the pause icon to a play icon.
Here's my JavaScript:
var audio = document.getElementById('audio');
audio.addEventListener('ended', stopAudio);
function stopAudio() {
audio.stop();
$('.play-pause .play').show();
$('.play-pause .pause').hide();
}
.. only the code inside is not executing once called. The audio is playing successfully and ending successfully, it's just not calling my function. What am I missing?
It is because you are using getElementById and passing audio when I think you mean to use getElementsByTagName, either that or you have the wrong id for the audio element.
I needed:
audio.stop;
Instead of...
audio.stop();
Which fixed it :)
The HTML Audio Element has no method stop(). The reason your event handler isn't "working" is because the line audio.stop(); throws an error and nothing below it will execute.
Your code should look like below in order to detect if your audio has ended. There is no way to detect if it has been stopped but you can detect if it has ended or been paused. If you are looking for the code for when it's paused you replace the "ended" with "pause"
document.getElementById('audio').addEventListener("ended",function() {
$('.play-pause .play').show();
$('.play-pause .pause').hide();
}

Control start position and duration of play in HTML5 video

We have a video (13 minutes long) which we would like to control using HTML5. We want to be able to let our users control and select the parts of the video they want to play. Preferably this control would be through 2 input fields. They would input start time (in seconds) in first box and input duration to play (in seconds) in second box. For example, they might want to start the video 10 seconds in and play for 15 seconds. Any suggestions or guidance on the Javascript needed to do this?
Note: I have found the following:
Start HTML5 video at a particular position when loading?
But it addresses only starting at a particular time, and nothing with playing the video for a specified length of time.
You could use the timeupdate event listener.
Save the start time and duration time to variable after loadedmetadata event.
// Set video element to variable
var video = document.getElementById('player1');
var videoStartTime = 0;
var durationTime = 0;
video.addEventListener('loadedmetadata', function() {
videoStartTime = 2;
durationTime = 4;
this.currentTime = videoStartTime;
}, false);
If current time is greater than start time plus duration, pauses the video.
video.addEventListener('timeupdate', function() {
if(this.currentTime > videoStartTime + durationTime){
this.pause();
}
});
If you are able to set start time and end time of video while setting the video url.
you can specify the start and end time in the url itself like
src="future technology_n.mp4#t=20,50"
it will play from 20th second to 50th second.
There are a lot of nuances to using the javascript solution proposed by Paul Sham. A much easier course of action is to use the Media Fragment URI Spec. It will allow you to specify a small segment of a larger audio or video file to play. To use it simply alter the source for the file you are streaming and add #t=start,end where start is the start time in seconds and end is the end time in seconds.
For example:
var start = document.getElementById('startInput').value;
var end = document.getElementById('endInput').value;
document.getElementById('videoPlayer').src = 'http://www.example.com/example.ogv#t='+start+','+end;
This will update the player to start the source video at the specified time and end at the specified time. Browser support for media fragments is also pretty good so it should work in any browser that supports HTML5.
Extend to michael hanon comments:
IE returns buffered.length = 0 and seekable.length = 0. Video doesn't play. So solution:
src="video.mp4#t=10,30"
will not works in IE. If you would like to support IE only way is to use javascript to seek video just after start from 0 second.

HTML5 video - Play event not firing

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.

If video = duration stop and rewind

I'm making a HTML5 video player. I want it so that when the movie stops the play these executes
video.pause();
video.currentTime=0;
document.getElementById('message').innerHTML="Finished";
I tried this but it didn't work
function rewsi() {
var video = document.getElementsByTagName('video')[0];
if (video.currentTime==video.duration) {
video.pause();
video.currentTime=0;
document.getElementById('message').innerHTML="Finished";
}
}
Anyone got a solution for this problem?
Problem = My lack of knowledge in JavaScript
Looking at the following question and asnwer:
HTML5 <video> callbacks?
I would assign a callback to be executed when the video has actually ended like so:
var Media = document.getElementsByTagName('video')[0];
var Message = document.getElementById('message');
Media.bind('ended',function(){
Message.innerHTML = "The media file has completed";
});
You also stated that when the media 'stops' you want to pause the video, can you describe your motives for doing that ?
The next on the agenda is the video resetting as such, looks like you want to set the position of the media to the start if the media stops, you must first make sure that your determining that the video has not been paused, as you do not want to reset the position if the user has gone to make a cup of coffee.
If you only want to set the media position when the movie has actually ended then this would be pointless (unless you have a valid reason to do so), the reason it would be pointless is that when the user clicks play after it has ended, the default action html5 media player takes is to set the position to 0.
The above solution should work out exactly right for you.
i will recommend using Kaltura HTML5 Video Library to help you manage the media player.
First, you can check if the video has ended by simply putting a condition on video.ended. Then you can set the time with this.currentTime(0);

Categories