I would like to use integrated Vimeo videos on a page and have them start playing as soon as the page is loaded and when the first video has finished, the second one starts. In my code I have an array of video ids but my problem is the video does not load.
<div id="headervideo"></div>
<script src="https://player.vimeo.com/api/player.js"></script>
<script>
//====================
document.addEventListener("DOMContentLoaded", function(event) {
var videos = ['240512614', '227735391']; // videos ids
var options = {
width: 640,
loop: true
};
var player = new Vimeo.Player('headervideo', options);
playMovie(player, videos)
})//end function
//====================
var playMovie = function(player, videos) {
if(!videos.length){
return false;
}
var video = videos.shift();
alert (video)
player.loadVideo(videos).then(function(id) {
alert("the video successfully loaded ")
player.getEnded().then(function(ended) {
playMovie(player, videos)
}).catch(function(error) {
console.warn(error)
});
}).catch(function(error) {
console.warn(error);
});
}//end function
//====================
</script>
Your first issue lies in
new Vimeo.Player('headervideo', options);
You cannot create a Vimeo.Player without specifying a video in the options object (or as an html attribute on an associated element).
So, specifying either:
var video = videos.shift();
var options = {
width: 640,
loop: true,
id: video
}
or:
var options = {
width: 640,
loop: true,
id: videos[0]
}
Will let you load the video.
But this will raise your second issue, that playMovie will not wait for your currently playing video to finish, but rather swap the video out immediately. getEnded() is not a synchronously blocking function.
What you want to do is instead listen on the ended event. And also turn of the loop: true as this will disable the ended event
document.addEventListener("DOMContentLoaded", function(event) {
window.videos = ['240512614', '227735391']; // videos ids
var video = videos.shift();
var options = {
width: 640,
loop: false,
id: video
};
window.player = new Vimeo.Player('headervideo', options);
window.player.on('ended', playNext);
window.player.play();
})//end function
//====================
var playNext= function() {
alert('foo');
if(!window.videos.length){
return false;
}
var video = window.videos.shift();
alert (video);
player.loadVideo(video).then(function(id) {
alert("the video "+id+" successfully loaded ");
player.play();
}).catch(function(error) {
console.warn(error)
});
}//end function
Related
Currently, the same video is only able to autoplay 1 time.
To reproduce: Click 1 svg play button, then click the X.
Then click the same svg play button a 2nd time.
You will find that the video does not autoplay.
How is that fixed in the code so that the same video can autoplay a 2nd time?
I would either be using autoplay, or player.playVideo(); to have the video play a 2nd time.
I'm not sure how it would work.
https://jsfiddle.net/2h7dgfe5/
const videoPlayer = (function makeVideoPlayer() {
const players = [];
const tag = document.createElement("script");
tag.src = "https://www.youtube.com/player_api";
const firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function createStopHandler(player) {
const stopButtons = document.querySelectorAll(".exit");
stopButtons.forEach(function stopButtonHandler(buttons) {
buttons.addEventListener("click", function buttonClickHandler() {
player.stopVideo();
});
});
}
function onPlayerReady(event) {
const player = event.target;
player.setVolume(100);
createStopHandler(player);
}
function addPlayer(video, settings) {
const defaults = {
height: 360,
host: "https://www.youtube-nocookie.com",
videoId: video.dataset.id,
width: 640
};
defaults.events = {
onReady: onPlayerReady
};
const playerOptions = combinePlayerOptions(defaults, settings);
const player = new YT.Player(video, playerOptions);
players.push(player);
return player;
}
return {
addPlayer
};
}());
const managePlayer = (function makeManagePlayer() {
const defaults = {
playerVars: {
autoplay: 1,
controls: 1,
disablekb: 1,
enablejsapi: 1,
fs: 0,
iv_load_policy: 3
}
};
The problem is coming from the way you init the player the first time. When the player is just created there is a onPlayerReady function that is being called. This function is not called on popup open a second time.
You need to keep references to the players and when popup is opened so you could find the player you want and do:
player.playVideo();
I see that you keep them here: const players = []; but you don't have access to this when you open the popup so you can't really call .playVideo().
I would invest some time into creating a structure that holds references for the player based on the popup so it would be something like:
const players = new Map();
// key can be anything you may use to relate:
// - HTML reference -> the element you click could be your key
// - string
// - other object
// - number
players.set(anyReasonableKey, playerInstance)
// then click handler would be something like this
function onPlayButtonClick(event) {
const key = event.target;
const p = players.get(key); // event target is the key, the play button.
// if there is no player
if(typeof player === "undefined"){
// the creation with autoplay option should handle fist start of video, because you need to wait for onPlayerReady event
makePlayer(key) // here you create it for the first time, and pass the key so you could do the following inside of the function:
// players.set(key, player)
} else {
p.playVideo(); // if player exists, just start playing video
}
}
playButton.addEventListener("click", onPlayButtonClick)
Or ... a bit easier way (but not preferrable) would be to re-create the player every time the user opens the popup, this way it will always autoplay based on your init config.
We have a laptop with one built-in webcam and 2 external USB webcams. I would like to receive images from all three webcams at the same time. I know that since 2018 this is possible.
I am using the following code to work with one camera, but how to display the image from three cameras at once?
<script>
var video = null;
var canvas = null;
var canvasContext = null;
var webimage = null;
var statusLabel = null;
function initVideo() {
video = document.getElementById("monitor");
statusLabel = document.getElementById("LBLSTATUS");
navigator.webkitGetUserMedia({video:true}, gotStream, noStream);
}
function setStatus(aStatus) {
statusLabel.innerHTML = aStatus;
}
function gotStream(stream) {
video.onerror = function () {
stream.stop();
streamError();
};
video.srcObject = stream;
//video.src = webkitURL.createObjectURL(stream); -> Deprecated
}
function noStream() {
setStatus('No camera available.');
}
function streamError() {
setStatus('Camera error.');
}
</script>
You need to get all 3 cameras deviceIDs. Once you get those, make 3 calls to getUserMedia, each with the respective camera ids.
navigator.mediaDevices.getUserMedia({
video: {
deviceId:{
exact: videoSource
},
},
}).then(function( video ) {
const localVidElem = document.getElementById( 'localVideo1' );
localVidElem.srcObject = video;
})
<video id="localVideo1"></video>
Make sure that you have the correct DeviceID and then assign it a srcObject. For more info about that, please read the official WebRTC docs.
I've added buttons to the page that when you click on each one, it first unloads the howl object and changes the src, and then new music is played. But the problem is that after changing src twice, the script does not work a third time
What does the following code do:
The how object creates howling
When you hit any button that has .play-btn, the source of each button puts in ._src sound and new music is played
<script>
var musicSrc = "";
var sound = 0;
var musicId= 0;
var soundCurrentTime ,soundTime = 0;
var soundPercent = 0;
var playInterval;
sound = new Howl({
src: '/uploads/tracks/'+$('.content > .music-list-player:first-of-type .play-btn').attr('track-file'),
volume: 1,
html5: true,
xhr: {
method: 'POST',
},
format : 'mp3',
onload: function () {
$('.player-container').removeClass('load-track'); //'Remove Music Loading Animation
soundTime = sound.duration(); //'Get Full Sound Time
soundPercent = (soundCurrentTime * 100)/soundTime; //'Get now Percent Played
$('.full-time#full-time').html(secondsToHms(soundTime)); //'Show Full Music Time in left Time Box
},
onplay:function () {
$('.player-container').removeClass('load-track'); //'Remove Music Loading Animation
playInterval= setInterval(playProgress,100);
$('.play-btn[playing="1"]').attr('player-target','pause');
},
onend: function () {
$('.play-btn[playing="1"]').attr('player-target','play'); //'Show Play Button
$('.player-progress-bar').css('width','0%'); //'Reset Progress Bar
$('.current-time').html("00:00"); //Set Current Time to 00:00
clearInterval(playInterval);
},
onpause: function () {
$('.player-container').removeClass('load-track'); //'Remove Music Loading Animation
$('#progress'+musicId+', #progress').css('width',soundPercent+'%');
$('.current-time').html('00:00');
$('.current-time#current-time , #current-time-'+musicId).html(secondsToHms(soundCurrentTime));
clearInterval(playInterval);
},
onloop: function () {
playInterval = setInterval(playProgress,100);
}
});
$('.music-list-player .play-btn').on('click', function () { //'It happens by Click the list play Button
$('.player-container').addClass('load-track');
var playerBtnClass = '.'+this.className;
var playingStatus = $(this).attr('player-target') == 'pause' ? playingStatus = 0 : playingStatus = 1;
musicId = this.id;
musicSrc = $(this).attr('track-file');
if (playingStatus){ //'Play btn is playing
if (sound._src !== '/uploads/tracks/'+musicSrc){ //'Music's changed
sound.stop();
sound.unload();
console.log(sound);
sound._src = '/uploads/tracks/'+musicSrc;
sound.load();
$('.player-progress-bar').css('width','0%'); //'Reset Progress Bar
$('.player-container').addClass('load-track'); //'add Music Loading Animation
}
$('.player-artist-name').html($(playerBtnClass+"#"+musicId+" + .artist-name ").html());
$('.player-music-name').html($(playerBtnClass+"#"+musicId+" + .artist-name + .music-name ").html());
$(this).attr('player-target','pause');
$(playerBtnClass+":not(#"+musicId+")").attr('player-target','play');
$('#play-btn').attr('player-target','pause');
sound.play();
}
else{ //'Play btn is not playing
$(this).attr('player-target','play');
$('#play-btn').attr('player-target','play');
sound.pause();
}
});
Here' my complete code for displaying and live recording audio and video (and later uploading the blob chunk into the server):
$(function () {
var handleSuccess = function(stream) {
var player = document.querySelector("#vid-user");
player.srcObject = stream;
console.log("Starting media recording")
var options = {mimeType: 'video/webm'};
var recordedChunks = [];
var mediaRecorder = new MediaRecorder(stream, options);
mediaRecorder.ondataavailable = function(e) {
console.log("Data available")
if (e.data.size > 0) {
recordedChunks.push(e.data);
var url = URL.createObjectURL(new Blob(recordedChunks));
console.log("URL: " + url)
}
}
mediaRecorder.start();
};
navigator.mediaDevices.getUserMedia({ audio: true, video: true })
.then(handleSuccess)
})
The video playback works, but the problem is that the mediaRecorder.ondataavailable is not triggered/called. What could be the problem here?
The start() method takes an optional parameter called timeslice. Unless you specify that parameter the dataavailable event only fires after you call stop() on the MediaRecorder.
https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/start
The solution is to set
mediaRecorder.start(1000); // where 1000 is the interval
Solution according to the documentation (https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder): Use MediaRecorder.start("time in milliseconds") to trigger 'dataavailable' event at the specified interval AND/OR use setTimeout(MediaRecorder.requestData(), "time in milliseconds"). I have a jsFiddle example here (not complete code, check the console messages only).
I play some audio file:
var audio = new Audio(audioUrl);
audio.play();
After start playing a need to send some ajax request.
How i can get callback onStartPlaying from audio class?
something like:
callback = function ( ){
...ajax...
}
audio.onstartplaying = callback;
Thank you.
SOLUTION
To use howler.js library.
https://github.com/goldfire/howler.js
var sound = new Howl({
urls: ['sound.mp3', 'sound.ogg', 'sound.wav'],
autoplay: true,
loop: false,
volume: 0.5,
onplay: function() {
console.log('On Play Callback');
}
});
Try this:
HEAD HTML:
<script src="http://kolber.github.io/audiojs/audiojs/audio.min.js"></script>
BODY HTML:
<span id="textbox">click the play button</span><br><br>
<audio src="http://kolber.github.io/audiojs/demos/mp3/juicy.mp3" preload="auto"></audio>
JavaScript:
function changeText(newtext) {
var span = document.getElementById('textbox');
while( span.firstChild ) span.removeChild( span.firstChild );
span.appendChild( document.createTextNode(newtext) );
}
audiojs.events.ready(function() {
var audios = document.getElementsByTagName('audio');
var player = audiojs.create( audios[0], {
play: function() {
changeText("Audio is Playing"); // change text to "Audio is Playing"
},
pause: function() {
changeText("Audio is Paused"); // change text to "Audio is Paused"
}
});
});
JS Fiddle: View Working Demo