VideoJS currentTime() always returning 0 - javascript

I'm using videoJs to load a video into an admin
platform built in react. I set up the player here :
else if (contentSource == 'arclight'){
var options = {
height:'216',
sources :[{
//src: this.state.video.url,
// type: 'video/mp4'
}]
}
var player = videojs('player',options,function onPlayerReady() {
videojs.log('Your player is ready!');
})
this.setState({
player:player,content: contentSource
});
}
My video is displayed in this tag :
<video id="player" class="player"
className={`video-js vjs-default-skin vjs-big-play-centered
${styles.vjs}`}
controls preload= "auto" data-
setup='{"example_option":true}'>
<source src={this.state.video.url} type= "video/mp4" />
<p className="vjs-no-js">
To view this video please enable JavaScript, and consider
upgrading to a web browser that
<a href= "http://videojs.com/html5-video-support"
target="_blank"> supports HTML5 video </a>
</p>
</video>
and lastly i'm trying to get the current time of the video that is playing in this method
handleCurrentButton(inputId, event){
event.preventDefault();
var timeMark =0;
if(this.state.content == 'vimeo'){
this.state.player.getCurrentTime().then(function(seconds){console.log(seconds)
timeMark=seconds;
VideosActions.updateVideoAttribute(inputId, timeMark);
}).catch(function(error){
});
}
else if(this.state.content == 'youtube') {
timeMark = Math.round(this.state.player.getCurrentTime());
VideosActions.updateVideoAttribute(inputId, timeMark);
}
else {
// timeMark = this.state.player.currentTime();
console.log(this.state.player.currentTime())
VideosActions.updateVideoAttribute(inputId, timeMark);
}
}
the problem is that the player.currentTime() call is always returning 0. The other two getCurrentTime's for Vimeo and Youtube work fine. what is the reason behind this? I tried to give enough context around this problem so that you would be able to figure it out.
Thanks for your help in advance!

The problem is getCurrentTime() returns a promise so you need to access the value of the time when the promise is resolved as a callback to the Promise's .then() function.
else {
this.state.player.currentTime().then(function(seconds){
console.log(seconds)
timeMark=seconds;
VideosActions.updateVideoAttribute(inputId, timeMark);
});
}

Worth making sure your server returning 206 response on the video HTTP request, otherwise players dont handle seek well.

Related

How to detect whether a video is on mute via JavaScript?

So far I've found out how to detect whether an audio element is paused or not, where I can use this function below (By the way please do tell me where is aud_play_pause function from and where I can learn more)
function aud_play_pause()
However, I have no clue how to detect whether a video is on mute, I only have the code below. By detection, I mean this code can run by itself without any event like clicking.
if ( $("video").prop('muted') ) {
$("#m-v").removeClass('on').addClass('off');
} else {
$("#m-v").removeClass('off').addClass('on');
};
or this, are they the same?
if (video.muted === true;) {
$("#m-v").removeClass('on').addClass('off');
} else {
$("#m-v").removeClass('off').addClass('on');
};
.prop() is a jQuery method. The html5 <video> tag does have a property muted. So the two code samples are checking the same property/attribute. Refer to this W3 page for a list of all events and properties.
In the example below, we use jQuery's .on() to bind event handlers to the video events. The function checkMuteStatus uses the code you provided and adds a few debugging output lines. It also uses $(document).ready() to wait until the DOM is loaded before binding the event handler. To read more about event delegation, refer to this jQuery page on the topic.
$(document).ready(function() {
$('#video').on('play pause ended timeupdate volumechange', checkMuteStatus);
});
function checkMuteStatus() {
var video = $('video');
var videoById = document.getElementById('video')
$('#console').append('prop: ', video.prop('muted') ? 'true' : 'false', ' .muted: ', videoById.muted ? 'true' : 'false', '<br />');
if ($("video").prop('muted')) {
$("#m-v").removeClass('on').addClass('off');
} else {
$("#m-v").removeClass('off').addClass('on');
};
}
#m-v.on {
color: #f00;
}
#m-v.off {
color: #0f0;
}
.float {
float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<video src="http://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.webm" controls="" id="video">
<p>Your browser doesn't support HTML5 video. Here is a link to the video instead.</p>
</video>
<div class="float">
<div id="m-v" class="on">Mute Status</div>
<div id="console"></div>
</div>
It is unknown where aud_play_pause is defined but maybe you are looking at something like the W3 audio example HTML/Elements/audio*

How to randomize in pairs?

I'm trying to randomize some videos that are both .webm and .mp4.
I have a two of each video for instance vid1.webm and vid1.mp4
I'd like to have the videos randomize and pull both at the same time into the video tag.
safari doesn't support .webm so that's why i would like to have .mp4 as a backup and need both to randomize into the browser on click.
I am loading them from an array and also can't figure out how the folder structure should be listed out, I would really like to keep them in an array as I am loading in several hundred
var randomImage = new Array();
randomVideo[0] = "videos/1.webm/ or mp4"; //not sure how to do the file structure
randomVideo[1] = "videos/2.webm/ or mp4"; //
randomVideo[2] = "videos/3.webm/ or mp4"; //
//trying to figure out this part
$(function() {
$('a.click').click(function(e) {
e.preventDefault();
var number = Math.floor(Math.random()*randomVideo.length);
$(this).html('<source src="'+randomVideo[number]+'" />');
});
});
$(function() {
$('a.click').click(function(e) {
e.preventDefault();
var number = Math.floor(Math.random()*randomVideo.length);
$(this).html('<source src="'+randomVideo[number]+'" type="video/mp4" /> )
}
})
html
<a href="#" class="click">
<section>
<video controls autoplay>
<script>
randomVideo()
</script>
</video>
</section>
</a>
If anyone can help me figure this out it would be greatly appreciated!
Can't figure it out, still learning.
You have multiple issues. Firstly your array name doesn't match (randomImage and randomVideo). Not sure why you are hooking the click event twice. One approach is to store the common parts of the path in the array and then concatenate the file ending. Also, I have no idea what you were trying to do with the img tag...
Anyway, the code below should help you, if I have understood what you are trying to do correctly.
var randomVideo = new Array();
// define your common video paths here
randomVideo[0] = "videos/1";
randomVideo[1] = "videos/2";
randomVideo[2] = "videos/3";
function randomiseVideos() {
var number = Math.floor(Math.random() * randomVideo.length);
$('#myvid').empty(); // clean up from last time
// now add 2 sources (will fall back appropriately depending on client support)
$('#myvid').append('<source src="' + randomVideo[number] + '.webm" type="video/webm">');
$('#myvid').append('<source src="' + randomVideo[number] + '.mp4" type="video/mp4">');
}
$(function () {
// Randomise on page load
randomiseVideos();
// handle click on test link
$('a.click').click(function (e) {
e.preventDefault();
randomiseVideos();
});
});
HTML:
Test Link
<section>
<video id="myvid" width="320" height="240" controls autoplay></video>
</section>
JS fiddle demo
The video element supports multiple sources https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_HTML5_audio_and_video
A very simple solution would be to store a list of video objects in your array:
var videos = [
[{type:'mpg', 'src':'blah.mpg'}, {type:'webm', 'src':'blah.webm'}],
[{type:'mpg', 'src':'blah2.mpg'}, {type:'webm', 'src':'blah2.webm'}],
];
...
var video = videos[randomIndex];
And use that to output sources like:
<video controls>
<source src="blah.mpg" type="video/ogg">
<source src="blah.webm" type="video/mp4">
Your browser does not support the <code>video</code> element.
</video>

HTML 5 Issues with Google IMA SDK

Okay i have searched al over for a decent example on how to get the HTML 5 IMA SDK from Google working.
I have pasted my code below, all that happens is the HTML 5 video shows up that's it no errors nothing. I don't think the Javascript is even running and I know its because I messed something up. Please help. I just want to display ads into an HTML 5 vid
I have substituted my VAST tag for Googles example tag and used a generic video I found on the web for the src video. Anyone have a suggestion on why this doesnt work.
<video id="videohtml5" width="720" height="405" controls="controls">
<source src="http://www.cncpts.me/complex/html5-IMA/NewBalance_NYCExperience_FINAL.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
var adsManager;
var adsLoader;
var clickTrackingOverlay = document.getElementById('clickTrackingOverlay');
var videoElement = document.getElementById('videohtml5');
var adsLoader = new google.ima.AdsLoader();
// Add event listeners
adsLoader.addEventListener(
google.ima.AdsLoadedEvent.Type.ADS_LOADED,
onAdsLoaded,
false);
adsLoader.addEventListener(
google.ima.AdErrorEvent.Type.AD_ERROR,
onAdError,
false);
// Create request object
var adsRequest = {
adTagUrl: "hhttp://pubads.g.doubleclick.net/gampad/ads?sz=400x300&iu=%2F6062%2Fiab_vast_samples&ciu_szs=300x250%2C728x90&impl=s&gdfp_req=1&env=vp&output=xml_vast2&unviewed_position_start=1&url=[referrer_url]&correlator=[timestamp]&cust_params=iab_vast_samples%3Dlinear",
adType: "video"
};
// Make request
adsLoader.requestAds(adsRequest);
function onAdsLoaded(adsLoadedEvent) {
// Get the ads manager
adsManager = adsLoadedEvent.getAdsManager();
adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, onAdError);
// Listen and respond to events which require you to pause/resume content
adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
onPauseRequested);
adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
onResumeRequested);
// Set a visual element on which clicks should be tracked for video ads
adsManager.setClickTrackingElement(clickTrackingOverlay);
try {
// Call play to start showing the ad.
adsManager.play(videoElement);
} catch (adError) {
// An error may be thrown if there was a problem with the VAST response.
}
}
function onAdError(adErrorEvent) {
// Handle the error logging.
console.log(adErrorEvent.getError());
}
function onPauseRequested() {
videoElement.pause();
// Setup UI for showing ads (e.g. display ad timer countdown,
// disable seeking, etc.)
// setupUIForAd();
}
function onResumeRequested() {
// Setup UI back for showing content.
// setupUIForContent();
videoElement.play();
}
</script>
figured it out next task is to learn how to run this on an embed object inside an iframe
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/uds?file=ima&v=1&nodependencyload=true"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#videohtml5").click(function(){
var adsManager;
var clickTrackingOverlay = document.getElementById('clickTrackingOverlay');
var videoElement = document.getElementById('videohtml5');
var adsLoader = new google.ima.AdsLoader();
// Add event listeners
adsLoader.addEventListener(
google.ima.AdsLoadedEvent.Type.ADS_LOADED,
onAdsLoaded,
false);
adsLoader.addEventListener(
google.ima.AdErrorEvent.Type.AD_ERROR,
onAdError,
false);
// Create request object
var adsRequest = {
adTagUrl: "http://pubads.g.doubleclick.net/gampad/ads?sz=400x300&iu=%2F6062%2Fiab_vast_samples&ciu_szs=300x250%2C728x90&impl=s&gdfp_req=1&env=vp&output=xml_vast2&unviewed_position_start=1&url=[referrer_url]&correlator=[timestamp]&cust_params=iab_vast_samples%3Dlinear",
adType: "video"
};
// Make request
adsLoader.requestAds(adsRequest);
function onAdsLoaded(adsLoadedEvent) {
// Get the ads manager
adsManager = adsLoadedEvent.getAdsManager();
adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, onAdError);
// Listen and respond to events which require you to pause/resume content
adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
onPauseRequested);
adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
onResumeRequested);
// Set a visual element on which clicks should be tracked for video ads
adsManager.setClickTrackingElement(clickTrackingOverlay);
try {
// Call play to start showing the ad.
adsManager.play(videoElement);
} catch (adError) {
// An error may be thrown if there was a problem with the VAST response.
}
}
function onAdError(adErrorEvent) {
// Handle the error logging.
console.log(adErrorEvent.getError());
}
function onPauseRequested() {
videoElement.pause();
// Setup UI for showing ads (e.g. display ad timer countdown,
// disable seeking, etc.)
// setupUIForAd();
}
function onResumeRequested() {
// Setup UI back for showing content.
// setupUIForContent();
videoElement.play();
}
});
});
</script>
<video id="videohtml5" width="720" height="405" controls="controls" onclick="">
<source src="#" type="video/mp4">
Your browser does not support the video tag.
</video>

YouTube iframe API: how do I control an iframe player that's already in the HTML?

I want to be able to control iframe based YouTube players. This players will be already in the HTML, but I want to control them via the JavaScript API.
I've been reading the documentation for the iframe API which explain how to add a new video to the page with the API, and then control it with the YouTube player functions:
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('container', {
height: '390',
width: '640',
videoId: 'u1zgFlCw8Aw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
That code creates a new player object and assigns it to 'player', then inserts it inside the #container div. Then I can operate on 'player' and call playVideo(), pauseVideo(), etc. on it.
But I want to be able to operate on iframe players which are already on the page.
I could do this very easily with the old embed method, with something like:
player = getElementById('whateverID');
player.playVideo();
But this doesn't work with the new iframes. How can I assign a iframe object already on the page and then use the API functions on it?
Fiddle Links: Source code - Preview - Small version
Update: This small function will only execute code in a single direction. If you want full support (eg event listeners / getters), have a look at Listening for Youtube Event in jQuery
As a result of a deep code analysis, I've created a function: function callPlayer requests a function call on any framed YouTube video. See the YouTube Api reference to get a full list of possible function calls. Read the comments at the source code for an explanation.
On 17 may 2012, the code size was doubled in order to take care of the player's ready state. If you need a compact function which does not deal with the player's ready state, see http://jsfiddle.net/8R5y6/.
/**
* #author Rob W <gwnRob#gmail.com>
* #website https://stackoverflow.com/a/7513356/938089
* #version 20190409
* #description Executes function on a framed YouTube video (see website link)
* For a full list of possible functions, see:
* https://developers.google.com/youtube/js_api_reference
* #param String frame_id The id of (the div containing) the frame
* #param String func Desired function to call, eg. "playVideo"
* (Function) Function to call when the player is ready.
* #param Array args (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
var iframe = document.getElementById(frame_id);
if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
}
// When the player is not ready yet, add the event to a queue
// Each frame_id is associated with an own queue.
// Each queue has three possible states:
// undefined = uninitialised / array = queue / .ready=true = ready
if (!callPlayer.queue) callPlayer.queue = {};
var queue = callPlayer.queue[frame_id],
domReady = document.readyState == 'complete';
if (domReady && !iframe) {
// DOM is ready and iframe does not exist. Log a message
window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
if (queue) clearInterval(queue.poller);
} else if (func === 'listening') {
// Sending the "listener" message to the frame, to request status updates
if (iframe && iframe.contentWindow) {
func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
iframe.contentWindow.postMessage(func, '*');
}
} else if ((!queue || !queue.ready) && (
!domReady ||
iframe && !iframe.contentWindow ||
typeof func === 'function')) {
if (!queue) queue = callPlayer.queue[frame_id] = [];
queue.push([func, args]);
if (!('poller' in queue)) {
// keep polling until the document and frame is ready
queue.poller = setInterval(function() {
callPlayer(frame_id, 'listening');
}, 250);
// Add a global "message" event listener, to catch status updates:
messageEvent(1, function runOnceReady(e) {
if (!iframe) {
iframe = document.getElementById(frame_id);
if (!iframe) return;
if (iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
if (!iframe) return;
}
}
if (e.source === iframe.contentWindow) {
// Assume that the player is ready if we receive a
// message from the iframe
clearInterval(queue.poller);
queue.ready = true;
messageEvent(0, runOnceReady);
// .. and release the queue:
while (tmp = queue.shift()) {
callPlayer(frame_id, tmp[0], tmp[1]);
}
}
}, false);
}
} else if (iframe && iframe.contentWindow) {
// When a function is supplied, just call it (like "onYouTubePlayerReady")
if (func.call) return func();
// Frame exists, send message
iframe.contentWindow.postMessage(JSON.stringify({
"event": "command",
"func": func,
"args": args || [],
"id": frame_id
}), "*");
}
/* IE8 does not support addEventListener... */
function messageEvent(add, listener) {
var w3 = add ? window.addEventListener : window.removeEventListener;
w3 ?
w3('message', listener, !1)
:
(add ? window.attachEvent : window.detachEvent)('onmessage', listener);
}
}
Usage:
callPlayer("whateverID", function() {
// This function runs once the player is ready ("onYouTubePlayerReady")
callPlayer("whateverID", "playVideo");
});
// When the player is not ready yet, the function will be queued.
// When the iframe cannot be found, a message is logged in the console.
callPlayer("whateverID", "playVideo");
Possible questions (& answers):
Q: It doesn't work!
A: "Doesn't work" is not a clear description. Do you get any error messages? Please show the relevant code.
Q: playVideo does not play the video.
A: Playback requires user interaction, and the presence of allow="autoplay" on the iframe. See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes and https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
Q: I have embedded a YouTube video using <iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />but the function doesn't execute any function!
A: You have to add ?enablejsapi=1 at the end of your URL: /embed/vid_id?enablejsapi=1.
Q: I get error message "An invalid or illegal string was specified". Why?
A: The API doesn't function properly at a local host (file://). Host your (test) page online, or use JSFiddle. Examples: See the links at the top of this answer.
Q: How did you know this?
A: I have spent some time to manually interpret the API's source. I concluded that I had to use the postMessage method. To know which arguments to pass, I created a Chrome extension which intercepts messages. The source code for the extension can be downloaded here.
Q: What browsers are supported?
A: Every browser which supports JSON and postMessage.
IE 8+
Firefox 3.6+ (actually 3.5, but document.readyState was implemented in 3.6)
Opera 10.50+
Safari 4+
Chrome 3+
Related answer / implementation: Fade-in a framed video using jQuery
Full API support: Listening for Youtube Event in jQuery
Official API: https://developers.google.com/youtube/iframe_api_reference
Revision history
17 may 2012
Implemented onYouTubePlayerReady: callPlayer('frame_id', function() { ... }).
Functions are automatically queued when the player is not ready yet.
24 july 2012
Updated and successully tested in the supported browsers (look ahead).
10 october 2013
When a function is passed as an argument, callPlayer forces a check of readiness. This is needed, because when callPlayer is called right after the insertion of the iframe while the document is ready, it can't know for sure that the iframe is fully ready. In Internet Explorer and Firefox, this scenario resulted in a too early invocation of postMessage, which was ignored.
12 Dec 2013, recommended to add &origin=* in the URL.
2 Mar 2014, retracted recommendation to remove &origin=* to the URL.
9 april 2019, fix bug that resulted in infinite recursion when YouTube loads before the page was ready. Add note about autoplay.
Looks like YouTube has updated their JS API so this is available by default! You can use an existing YouTube iframe's ID...
<iframe id="player" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com" frameborder="0"></iframe>
...in your JS...
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange() {
//...
}
...and the constructor will use your existing iframe instead of replacing it with a new one. This also means you don't have to specify the videoId to the constructor.
See Loading a video player
You can do this with far less code:
function callPlayer(func, args) {
var i = 0,
iframes = document.getElementsByTagName('iframe'),
src = '';
for (i = 0; i < iframes.length; i += 1) {
src = iframes[i].getAttribute('src');
if (src && src.indexOf('youtube.com/embed') !== -1) {
iframes[i].contentWindow.postMessage(JSON.stringify({
'event': 'command',
'func': func,
'args': args || []
}), '*');
}
}
}
Working example:
http://jsfiddle.net/kmturley/g6P5H/296/
My own version of Kim T's code above which combines with some jQuery and allows for targeting of specific iframes.
$(function() {
callPlayer($('#iframe')[0], 'unMute');
});
function callPlayer(iframe, func, args) {
if ( iframe.src.indexOf('youtube.com/embed') !== -1) {
iframe.contentWindow.postMessage( JSON.stringify({
'event': 'command',
'func': func,
'args': args || []
} ), '*');
}
}
Thank you Rob W for your answer.
I have been using this within a Cordova application to avoid having to load the API and so that I can easily control iframes which are loaded dynamically.
I always wanted the ability to be able to extract information from the iframe, such as the state (getPlayerState) and the time (getCurrentTime).
Rob W helped highlight how the API works using postMessage, but of course this only sends information in one direction, from our web page into the iframe. Accessing the getters requires us to listen for messages posted back to us from the iframe.
It took me some time to figure out how to tweak Rob W's answer to activate and listen to the messages returned by the iframe. I basically searched through the source code within the YouTube iframe until I found the code responsible for sending and receiving messages.
The key was changing the 'event' to 'listening', this basically gave access to all the methods which were designed to return values.
Below is my solution, please note that I have switched to 'listening' only when getters are requested, you can tweak the condition to include extra methods.
Note further that you can view all messages sent from the iframe by adding a console.log(e) to the window.onmessage. You will notice that once listening is activated you will receive constant updates which include the current time of the video. Calling getters such as getPlayerState will activate these constant updates but will only send a message involving the video state when the state has changed.
function callPlayer(iframe, func, args) {
iframe=document.getElementById(iframe);
var event = "command";
if(func.indexOf('get')>-1){
event = "listening";
}
if ( iframe&&iframe.src.indexOf('youtube.com/embed') !== -1) {
iframe.contentWindow.postMessage( JSON.stringify({
'event': event,
'func': func,
'args': args || []
}), '*');
}
}
window.onmessage = function(e){
var data = JSON.parse(e.data);
data = data.info;
if(data.currentTime){
console.log("The current time is "+data.currentTime);
}
if(data.playerState){
console.log("The player state is "+data.playerState);
}
}
I was having issues with the above examples so instead, I just inserted the iframe on click in with JS with autoplay in the source and it works fine for me. I also had the possibility for Vimeo or YouTube so I needed to be able to handle that.
This solution isn't amazing and could be cleaned up but this worked for me. I also don't like jQuery but the project was already using it and I was just refactoring existing code, feel free to clean up or convert to vanilla JS :)
<!-- HTML -->
<div class="iframe" data-player="viemo" data-src="$PageComponentVideo.VideoId"></div>
<!-- jQuery -->
$(".btnVideoPlay").on("click", function (e) {
var iframe = $(this).parents(".video-play").siblings(".iframe");
iframe.show();
if (iframe.data("player") === "youtube") {
autoPlayVideo(iframe, iframe.data("src"), "100%", "100%");
} else {
autoPlayVideo(iframe, iframe.data("src"), "100%", "100%", true);
}
});
function autoPlayVideo(iframe, vcode, width, height, isVimeo) {
if (isVimeo) {
iframe.html(
'<iframe width="' +
width +
'" height="' +
height +
'" src="https://player.vimeo.com/video/' +
vcode +
'?color=ff9933&portrait=0&autoplay=1" frameborder="0" allowfullscreen wmode="Opaque"></iframe>'
);
} else {
iframe.html(
'<iframe width="' +
width +
'" height="' +
height +
'" src="https://www.youtube.com/embed/' +
vcode +
'?autoplay=1&loop=1&rel=0&wmode=transparent" frameborder="0" allowfullscreen wmode="Opaque"></iframe>'
);
}
}
One quick solution, if requests are not an issue, and you're wanting this behavior for something like a show/hide video, is to remove/add the iframe, or cleaning and filling the src.
const stopPlayerHack = (iframe) => {
let src = iframe.getAttribute('src');
iframe.setAttribute('src', '');
iframe.setAttribute('src', src);
}
The iframe will be removed, stop to play and will be loaded right after that. In my case I've improved the code to only set the src again on lightbox open, so the load will only happen if user demands to see the video.

New to Javascript, need help with HTML5 audio "playlist"

im trying to create a sort of playlist feature that will work on the iPhone using a combination of HTML5 and javascript. I'm very new to the platform and I was hoping maybe someone here could help me identify the problem with my code. The first song properly autoplays, but when it ends the next one does not load and play. The javascript code for my site is provided below, thanks in advance. (my apologies if this code is terribly messed up, i assembled this from what iv learned and what i could find different places online)
<script type="text/javascript">
var songname="Bottoms Up";
var counter=1;
var totalsongs=3;
while (counter<=totalsongs-1) {
document.write(<h2>songname</h2>);
switch (counter) {
case 1:
var nextSong="audio/Hey.mp3";
var audioPlayer=document.getElementById('audioPlayer');
audioPlayer.onend = function() {
audioPlayer.src = nextSong;
songname="Hey";
counter=(counter+1);
if(counter>totalsongs-1) {
counter=1;
} //if close
} //onend function close
case 2:
var nextSong="audio/I Like It.mp3";
var audioPlayer=document.getElementById('audioPlayer');
audioPlayer.onend = function() {
audioPlayer.src = nextSong;
songname="I Like It";
counter=(counter+1);
if(counter>totalsongs-1) {
counter=1;
} //if close
} //onend function close
} //switch close
} //while close
</script>
<center><audio src="audio/Bottoms Up.mp3" autoplay controls /></center>
A few things:
Give the audio element an id:
<audio src="audio/Bottoms Up.mp3" autoplay controls id="audioPlayer" /></center>
Use arrays instead of many variables:
var songs=({{"title": "First title","filename":"firstfile.mp3"},
{"title": "Second title","filename":"secondfile.mp3"}});
Listen for the event ended like this:
document.getElementById("audioPlayer").addEventListener("ended", nextSong, false);
And put the script in the <head> element.
var audioPlayer=document.getElementById('audioPlayer');
… will error, since the element doesn't have an id.

Categories

Resources