Is there any way to pause and rewind to 0s a HTML5 video? Or just simply stop?
I got a jQuery popup, so when someone clicks on it, the popup shows up and the video plays, and when you hit the close button the video pauses. So what I'm trying to do is that if you click again the button to show the popup the video begins in the start position (0 secs).
Thanks.
You can get a reference to your jquery video element upon opening it (or closing the popup) and pause it using pause(), and then set the "currentTime" property to 0 to go back to the beginning.
Here's a reference to the documentation for currentTime.
here's a code sample:
var mediaElement = document.getElementById("video");
mediaElement.pause();
mediaElement.currentTime = 0;
To have a proper stop (pause & rewind) functionality you could do the following:
var video = document.getElementById('vidId');
// or video = $('.video-selector')[0];
video.pause();
video.currentTime = 0;
video.load();
Note: This is the only version that worked for me in chrome using nodejs (meteorjs) in the backend, serving webm & ogg files
Just call the pause() method of the video element. To reset the time, set currentTime to 0 (or any other value if needed, in seconds).
To reset a video to 0 seconds in jQuery:
$('#video')[0].currentTime = 0;
Or, in vanilla JS (Although this has been pointed out above):
var video = document.getElementById('video');
video.currentTime = 0;
Related
I have a slick.js slider that contains video and I want the slider to pause once it reaches a video slide and resume cycling once the video finishes without user interaction. I can get this functionality to work with the first video in a cycle but on the second video slide, the slider will not resume once the video completes.
Fiddle
I have a console log that writes out when the video completes but it won't say anything once the second video completes. I believe it is not seeing the function to play the slick slider.
function myHandler(e) {
console.log('Video Complete')
$('.sliderMain').slick('slickPlay');
}
You were only binding the first video tag to your myHandler function:
// It only gets the first element
var video = document.getElementsByTagName('video')[0];
video.addEventListener('ended',myHandler,false);
Since you're using jQuery, you can bind an event when the videos have ended like that:
$('video').on('ended',function(){
console.log('Video Complete')
$('.sliderMain').slick('slickPlay');
});
jQuery demo
The JavaScript equivalent would be so:
var videos = document.getElementsByTagName('video');
for (var i=0; i<videos.length; i++) {
videos[i].addEventListener('ended',myHandler,false);
}
JavaScript demo
SlickSlider is responsive and needs to work 360 (across all devices).
Your solution will not work on mobile, since autoplay of a video is forbidden.
Also this solution allows multiple videos to be playing at once, which is sub-optimal.
A better solution would be to pause the carousel only when the video is played by the user, and resume the carousel (pausing the video) when a slide is detected.
This works also on mobile devices. Just make sure, you don't serve a video tag on mobile. Before outputting your slide via PHP template, just check the user agent and serve a fallback image instead. Then use this for your video/autoplay/resume issue:
$('.homepage .hero-slider').on('afterChange', function(event, slick, currentSlide, nextSlide) {
var $active = $('.slick-slide.slick-current.slick-active');
var video = $active.find('video');
if (video.length == 1) {
var $slickInstance = $(this);
// play() only works with a valid id as selector :)
var video = document.getElementById(video.attr('id'));
video.play();
$slickInstance.slick('slickPause');
video.addEventListener('ended', function () {
$slickInstance.slick('slickPlay');
}, false);
}
});
I have a card matching game that I created here:
http://ewands.no-ip.biz/intern/guangjian/card/
The problem that I have is that I am unable to pause or mute the currently playing sound effect when a card is flipped, so if I immediately click the second card, no sound is heard. Using either pause and muted does not work. Any ideas?
//flipping_sound.pause(); does not work
//flipping_sound.muted; does not work
flipping_sound.play();
i'am using jquery and it's help for me:
flipping_sound.get(0).pause();
flipping_sound.get(0).currentTime = 0;
flipping_sound.get(0).play();
first you need to check if is playing with this:
function isPlaying(audioElement) { return audioElement.paused; }
and if the audio is playing you need change the position of the audio with this
function changeAudioPosition(audioElement) { audioElement.currentTime = 0; }
and if the audio is not playing just play again
Im trying to make a video player work in all browsers. There is
more then one video and every time you click on demo reel it plays the
video and if you click the video 1 the other video plays. How can i
make them both work in all browsers? Here is my html and javascript
html
<video id="myVideo" controls autoplay></video>
<div>
Demo Reel</div>
video 1</div>
</div>
javascript
function changeVid1() {
var changeStuff = document.getElementById("myVideo");
changeStuff.src = "video/demoreel.mp4"
}
function changeVid2() {
var changeStuff = document.getElementById("myVideo");
changeStuff.src = "video/video1.mp4";
}
After you switch the source of the video, you need to run .load() on it to force it to load the new file. Also, you need to provide multiple formats, because there is no video codec supported by all browsers.
First, set up your sources like this:
var sources = [
{
'mp4': 'http://video-js.zencoder.com/oceans-clip.mp4',
'webm':'http://video-js.zencoder.com/oceans-clip.webm',
'ogg':'http://video-js.zencoder.com/oceans-clip.ogv'
}
// as many as you need...
];
Then, your switch function should look like this:
function switchVideo(index) {
var s = sources[index], source, i;
video.innerHTML = '';
for (i in s) {
source = document.createElement('source');
source.src = s[i];
source.setAttribute('type', 'video/' + i);
video.appendChild(source);
}
video.load();
video.play(); //optional
}
See a working demo here.
This gives the browser a list of different formats to try. It will go through each URL until it finds one it likes. Setting the "type" attribute on each source element tells the browser in advance what type of video it is so it can skip the ones it doesn't support. Otherwise, it has to hit the server to retrieve the header and figure out what kind of file it is.
This should work in Firefox going back to 3.5 as long as you provide an ogg/theora file. And it will work in iPads, because you only have one video element on the page at a time. However, auto-play won't work until after the user clicks play manually at least once.
For extra credit, you can append a flash fallback to the video element, after the source tags, for older browsers that don't support html5 video. (i.e., IE < 9 - though you'll need to use jQuery or another shim to replace addEventListener.)
Having
var audio = new Audio("click.ogg")
I play the click sound when needed by
audio.play()
However, sometimes user is so fast that a browser does not play the audio at all (probably when still playing a previous play request). Is this issue related to preload?
How can I force a browser to stop playing and start over? There is no stop, just pause in HTML5 audio component, correct? What workaround can be used here?
Update - Additional note:
I have multiple checkbox-like div elements with a touchend event. When such event is triggered, the elements visually change, a sound is played and an internal variable is set accordingly. If user tap on these elements slowly, everything works nicely. If tap fast, the sound is often completely skipped...
The simplest solution is to just reset the audio currentTime and ensure it's playing using the play() method. Checking if the audio is playing is not necessary as subsequent play() invocations will not do anything.
audio.currentTime = 0;
audio.play();
This is the code I've been using and it's working for me:
if(audioSupport.duration > 0 && !audioSupport.paused){
//already playing
audioSupport.pause();
audioSupport.currentTime = 0;
audioSupport.play();
}else{
//not playing
audioSupport.play();
}
I noticed that on Firefox, playing a sound again and again really fast (like a short ticking sound) will skip beats often. The best solution I got was to simply call cloneNode and play each sound that way. Its not perfect (compared to Chrome where it sounds flawless):
var audio = document.getElementById('myaudio');
setInterval(function() {
audio.cloneNode().play();
}, 100);
The only way i found how to play a short sound very quickly (so quick that the 2nd sound starts before the first ends) is to actually load 5 or 10 and if you have to play again but are already playing, just go to the next, which is not playing:
var soundEls = [];//load 10 audios instead of 1
for(var i=0;i<10;i++){
var soundEl = document.createElement('audio');
soundEl.src = url;
soundEl.preload = 'auto';
$(this._soundEl).append(soundEl);
soundEls.push(soundEl);
}
var soundElIndex = 0;
return {play:function(){
var soundEl = soundEls[soundElIndex];
if(soundEl.duration > 0 && !soundEl.paused){
//already playing, switch to next soundEl
soundElIndex++;
if(!soundEls[soundElIndex]) soundElIndex=0;
soundEls[soundElIndex].play();
}else{
//not playing
soundEl.play();
}
}};
Result of this is you can actually play the same sound over itself.
Probably not the right way to do it though.
I am writing a Browser Plugin and need to find a way to get the current time a YouTube Video playing on YouTube using JavaScript. I have been playing around in the Chrome JavaScript Console and haven't had any luck.
It appears that the chrome API only works with embedded video players not a video that is playing on on youtube.com. One option I looked into is in the share section of a video their is an input box for the "start at:" time that contains the current time of the video. I have tried using .value and .text on this input box and they both return undefined? Does anyone have any ideas?
ytplayer = document.getElementById("movie_player");
ytplayer.getCurrentTime();
See the api
Update: if it didn't work, also try player.playerInfo.currentTime (codepen live example)
Depends on what you want
player.getCurrentTime():Number
Returns the elapsed time in seconds since the video started playing.
player.getDuration():Number
Returns the duration in seconds of the currently playing video. Note
that getDuration() will return 0 until the video's metadata is loaded,
which normally happens just after the video starts playing.
http://code.google.com/apis/youtube/js_api_reference.html
Finally I found how to make it work on iOS (and Android too).
Actually, the whole youtube js api was broken for me if run on mobile browser.
Problem solved by creating player using new YT.Player as described in YouTube IFrame API.
Please note: only creating <iframe> from <div> placeholder works for mobile browsers at the time. If you try to use existing <iframe> in new YT.Player call, as mentioned in IFrame API, this will not work.
After player created, it's possible to use player.getCurrentTime() or player.getDuration() with player instance created.
Note: I had no luck calling this methods on player obtained with
player = document.getElementById(...) (from #JosephMarikle answer).
Only created player instance worked in mobile browsers.
Useful links:
YouTube IFrame API
YouTube JavaScript API
YouTube Player Demo
You can use Html5 Video API on youtube.com
var htmlVideoPlayer = document.getElementsByTagName('video')[0];
htmlVideoPlayer.currentTime
Note: It's not gonna work on Youtube Iframe API because Iframes are isolated. You cannot access the context of a Youtube IFrame .
In 2020, this works:
player.playerInfo.currentTime
full code:
see it live on codepen
Just FYI, There is a new iframe API for the YouTube player:
https://developers.google.com/youtube/iframe_api_reference
document.querySelector('video').currentTime
Stop at specific time youtube video and show notification box in GWD
<script>
var yid = document.getElementById("gwd-youtube_1");
var idBox = document.getElementById("box1");
pausing_function = function(event) {
var aa = setInterval(function() {
if (yid.getCurrentTime() > 8.0 && yid.getCurrentTime() < 8.1) {
yid.pause(yid);
idBox.style.opacity = 1;
console.log(yid.getCurrentTime() + "playing")
clearInterval(aa);
yid.removeEventListener("playing", pausing_function);
}
}, 100)
}
yid.addEventListener("playing", pausing_function);
var pausing_function_1 = function() {
if (yid.getCurrentTime() > 8.1) {
console.log(yid.getCurrentTime() + "pause")
// remove the event listener after you paused the playback
yid.removeEventListener("playing", pausing_function);
}
};
</script>
play video and hide notification
<script type="text/javascript" gwd-events="handlers">
window.gwd = window.gwd || {};
gwd.pauseVideo = function(event) {
var idBox = document.getElementById("box1");
idBox.style.opacity = 0;
};
</script>
<script type="text/javascript" gwd-events="registration">
// Support code for event handling in Google Web Designer
// This script block is auto-generated. Please do not edit!
gwd.actions.events.registerEventHandlers = function(event) {
gwd.actions.events.addHandler('gwd-youtube_1', 'playing', gwd.pauseVideo, false);
};
gwd.actions.events.deregisterEventHandlers = function(event) {
gwd.actions.events.removeHandler('gwd-youtube_1', 'playing', gwd.pauseVideo, false);
};
document.addEventListener("DOMContentLoaded", gwd.actions.events.registerEventHandlers);
document.addEventListener("unload", gwd.actions.events.deregisterEventHandlers);
</script>