play video in loop using setTimeout - javascript

I want to play videos in a loop. For some reason I don't want change video src on ended event.
So I created video elements for each video in a loop. Also I have video src and durations in array.
here is my idea:
Only current playing video tag can be visible. Others will be hided.
Instead of using ended event, I want to use setTimeout function. Video's duration will be delay parameter.
But they all play together. I couldn't make them play in order.
Here is what I done so far:
videoArray = [
{"video":video1.mp4, "duration": 5},
{"video":video2.mp4, "duration": 7},
{"video":video3.mp4, "duration": 9},
{"video":video4.mp4, "duration": 10},
]
for (var j = 0; j < videoArray.length; j++){
var video = document.createElement("video");
video.src=videoArray[j];
video.id="video-"+j;
video.preload = "metadata";
video.type="video/mp4";
video.autoplay = true;
video.style.display="none";
document.body.appendChild(video);
}
for (var count = 0; count < videoArray.length; count++) {
(function(num){
setTimeout(function() {
videoArray[num].video.style.display="block";
videoArray[num].video.play();
}, 1000 * videoArray[num].duration);
videoArray[num].video.style.display="none";
})(count);
}

Disclaimer
I know that the question was asked without the ended event, but I do not think that set time out is the way to go.
Think of the scenario where you have video buffering, or slowing down for any reason, your setTimeout will be out of sync.
At the bottom I've added another solution that answers the requirement of not using the ended event, but again, I do not recommend using it.
Solution
The idea is to have an event listener to the end of the video, in that case, even if you run the video on a different speed you are still going to run the next video regardless of the duration.
Another benefit is that you do not need to know the duration of the videos in the first place.
PS.
the event listener that you need to listen to is video.addEventListener("ended", callback);
You are more than welcome to run the code or to have a look at a working example I've created for you
Working Example
const videoUrls = [
'https://videos-play-loop.netlify.com/video1.mp4',
'https://videos-play-loop.netlify.com//video2.mp4',
'https://videos-play-loop.netlify.com//video3.mp4',
];
const createVideo = ({id, src, width, cls = 'video', display = 'block', playbackRate = 1, muted = true, type = 'video/mp4', autoplay = false, controls = true}) => {
const videoElement = document.createElement("video");
videoElement.id = id;
videoElement.src = src;
videoElement.classList.add(src);
videoElement.type = type;
videoElement.autoplay = autoplay;
videoElement.controls = controls;
videoElement.style.display = display;
videoElement.muted = muted;
videoElement.playbackRate = playbackRate;
return videoElement;
};
const addVideos = (container, videoUrls) => {
const videos = videoUrls.map((url, index) => {
const first = index === 0;
const display = first ? 'block' : 'none';
return createVideo({id: `video-${index}`, src: url,display, width: 640, autoplay: first, playbackRate: 3});
});
videos.forEach((video, index) => {
const last = index === videos.length - 1;
const playNext = (element) => {
element.target.style.display = "none";
const nextElementIndex = last ? 0 : index + 1;
const nextElement = videos[nextElementIndex];
nextElement.autoplay = true;
nextElement.style.display="block";
nextElement.load();
};
video.addEventListener("ended", playNext);
container.appendChild(video)
});
};
const videoWrapper = document.getElementById('video-wrapper');
addVideos(videoWrapper, videoUrls);
#video-wrapper video {
max-width: 600px;
}
<div id="video-wrapper"></div>
Working solution with setTimeout (please use the solution above)
const videoUrls = [{
url: `https://videos-play-loop.netlify.com/video3.mp4`,
duration: 3,
},
{
url: `https://videos-play-loop.netlify.com/video2.mp4`,
duration: 4
},
{
url: `https://videos-play-loop.netlify.com/video1.mp4`,
duration: 5
}
];
const createVideo = ({
id,
src,
width,
cls = 'video',
display = 'block',
duration,
playbackRate = 1,
muted = true,
type = 'video/mp4',
autoplay = false,
controls = true
}) => {
const videoElement = document.createElement("video");
videoElement.id = id;
videoElement.src = src;
videoElement.classList.add(src);
videoElement.type = type;
videoElement.autoplay = autoplay;
videoElement.controls = controls;
videoElement.style.display = display;
videoElement.muted = muted;
videoElement.playbackRate = playbackRate;
videoElement.setAttribute('data-duration', duration);
return videoElement;
};
const playNext = (videos, index) => {
const current = videos[index];
const activeVideoDuration = parseInt(current.dataset.duration) * 1000;
setTimeout(() => {
const last = index === videos.length - 1;
current.style.display = "none";
current.pause();
const activeVideoIndex = last ? 0 : index + 1;
const next = videos[activeVideoIndex];
next.autoplay = true;
next.style.display = "block";
next.load();
next.play();
playNext(videos, activeVideoIndex);
}, activeVideoDuration);
};
const addVideos = (container, videoUrls) => {
const videos = videoUrls.map((video, index) => {
const {
url,
duration
} = video;
const first = index === 0;
const display = first ? 'block' : 'none';
return createVideo({
id: `video-${index}`,
src: url,
duration,
display,
width: 640,
autoplay: first,
});
});
videos.forEach(video => container.appendChild(video));
playNext(videos, 0);
};
const videoWrapper = document.getElementById('video-wrapper');
addVideos(videoWrapper, videoUrls);
#video-wrapper video {
max-width: 600px;
}
<div id="video-wrapper"></div>

You could hold the duration of the videos in a variable and the accumulate this variable with the previous video duration and set this a the setTimeOut duration.
Note that the time of the videos is in seconds. And for the first video to play user has to interact otherwise the video will not play.
Working Example:
function startVideos(event) {
event.target.style.display= "none";
(function() {
videoArray = [
{
video:
"http://techslides.com/demos/sample-videos/small.mp4",
duration: 5
},
{
video:
"http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",
duration: 60
},
{
video:
"https://mobamotion.mobatek.net/samples/sample-mp4-video.mp4",
duration: 120
},
{
video:
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
duration: 600
}
];
let videArrayElem = [];
for (var j = 0; j < videoArray.length; j++) {
var video = document.createElement("video");
video.src = videoArray[j].video;
video.id = "video-" + j;
video.preload = "metadata";
video.type = "video/mp4";
video.autoplay = false;
video.controls= true;
video.style.display = "none";
videArrayElem.push(video);
document.body.appendChild(video);
}
let prviousVideoDuration = 0;
for (var count = 0; count < videoArray.length; count++) {
(function(num) {
setTimeout(function() {
videArrayElem[num].style.display = "block";
videArrayElem[num].play();
}, prviousVideoDuration);
prviousVideoDuration += 1000 * videoArray[num].duration;
videArrayElem[num].style.display = "none";
})(count);
}
})();
}
video {
height: 100px;
width: 100px;
display: inline-block;
margin: 4px;
float: left;
}
<button type="button" onclick="startVideos(event)">Start Video Demo</button>

Aside from the facts that you are trying to achieve something strange, and that your code example will not compile. As I see it, you've got it.
The only missing thing is pause() and display = "none". With minimum edits you have what you need.
const videoArray = [
{"video":"video1.mp4", "duration": 5}, // of cause you need ""
{"video":"video2.mp4", "duration": 7},
{"video":"video3.mp4", "duration": 9},
{"video":"video4.mp4", "duration": 10},
]
for (let j = 0; j < videoArray.length; j++){
const video = document.createElement("video");
// you need to save DOM nodes somewhere to use them in the second loop
videoArray[j].video_el = video
video.src=videoArray[j].video; // `.video` is added
video.id="video-"+j;
video.preload = "metadata";
video.type="video/mp4";
video.autoplay = true;
video.style.display="none";
document.body.appendChild(video);
}
for (var count = 0; count < videoArray.length; count++) {
(function(num){
setTimeout(function() {
// add this to hide previous video node and stop video from playing
if( num ) {
videoArray[num-1].video_el.style.display="none";
videoArray[num-1].video_el.pause()
}
// videoArray[num].video - is a string, not a DOM node
// so, you need to change this:
// videoArray[num].video.style.display="block";
// for this:
videoArray[num].video_el.style.display="block";
// no need. `autoplay` is set to `true` in the first loop
// videoArray[num].video_el.play();
}, 1000 * videoArray[num].duration);
// no need. already done in the first loop
// videoArray[num].video_el.style.display="none";
})(count);
}
But there is a lot of flaws:
setTimeout does not care about network delays and other time related issues, so most probably your video sequence will not play seamlessly.
Because of the first flow and because I doubt that duration values are exact you should use pause().
As #IslamElshobokshy noted in comments to your question using play/pause is not so simple.
If user opens the page and does nothing more, you'll get:
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
in Chrome. And
Autoplay is only allowed when approved by the user, the site is activated by the user, or media is muted.
NotAllowedError: The play method is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
in Firefox.
So you'd probably be better off with the ended event after all, and with muted attribute (to mitigate the last issue):
for (let j = 0; j < videoArray.length; j++){
const video = document.createElement("video")
videoArray[j].video_el = video
video.src = videoArray[j].video
video.id = "video-"+j
video.preload = "metadata"
video.type = "video/mp4"
video.autoplay = true
// show the first video right away
if( j !== 0 ) video.style.display = "none"
// set muted attribute
video.muted = "muted"
// play next video after the previous had ended
video.addEventListener('ended', (num => function() {
this.style.display = "none";
if( num !== videoArray.length-1 ) {
videoArray[num+1].video_el.style.display="block";
// only needed if `muted` is not set
videoArray[num+1].video_el.play();
}
})(j), false);
document.body.appendChild(video);
}
If muted attribute is not the option, you can add some event listeners on the body to call play() on the first video as soon as the user starts interaction with the page. And maybe you would like to read more about autoplay here: https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

Related

JavaScript play() of audio is not working, TypeError: this.kickAudio.play is not function?

this.kickAudio.play(); is not playing i dont know why?? Please help
I am trying to play the audio by loop over the div but some how audio file is not playing
class DrumKit {
constructor() {
this.pads = document.querySelectorAll(".pad");
this.playBtn = document.querySelector(".play");
this.kickAudio = document.querySelectorAll(".kick-sound");
this.snareAudio = document.querySelectorAll(".snare-sound");
this.hithatAudio = document.querySelectorAll(".hithat-sound");
this.index = 0;
this.bpm = 150;
}
activePad() {
this.classList.toggle("active");
}
repeat() {
let step = this.index % 8;
const activeBars = document.querySelectorAll(`.b${step}`);
console.log(step);
// Looping over the pads for animation
activeBars.forEach((bar) => {
bar.style.animation = `playTrack 0.3s alternate ease-in-out 2`;
// Check for the active pad
if (bar.classList.contains("active")) {
if (bar.classList.contains("kick-pad")) {
this.kickAudio.currentTime = 0;
this.kickAudio.play();
}
}
});
this.index++;
}
start() {
const interval = (60 / this.bpm) * 1000;
setInterval(() => {
this.repeat();
}, interval);
}
}
const drumKit = new DrumKit();
drumKit.pads.forEach((pad) => {
pad.addEventListener("click", drumKit.activePad);
pad.addEventListener("animationend", function () {
// this.style.animation = '';
});
});
drumKit.playBtn.addEventListener("click", function () {
drumKit.start();
});
this.kickAudio.play(); is not playing i dont know why?? Please help
I am trying to play the audio by loop over the div but some how audio file is not playing

How to prevent a video array from playing the same video twice?

I'm trying to play video1 to 3 without playing the video twice. I'm using videos.shift(); to remove the first video from the array, but I'm not sure how to remove the other 2 videos after they play once.
var videos = ["video1", "video2", "video3"];
videos.shift();
var player1 = document.getElementById("video");
function setMp4Source1() {
var currentVideoIndex = Math.floor(Math.random() * videos.length);
var currentVideo = "videos/" + videos[currentVideoIndex] + ".mp4";
player1.src = currentVideo;
player1.load();
player1.play();
}
player1.addEventListener('ended', nextVideo, false);
function nextVideo() {
setMp4Source1();
}
If I understand this correctly, videos is a queue of videos that need to be played in order, then nothing else.
I would normalize all the queue management into the nextVideo() function, so that there was nothing special about the first time you play. Thus:
var videos = ["video1", "video2", "video3"]
var player1 = document.getElementById("video")
function setMp4Source1(theVideo) {
var currentVideo = "videos/" + theVideo + ".mp4"
player1.src = currentVideo
player1.load()
player1.play()
}
player1.addEventListener('ended', nextVideo, false)
function nextVideo() {
let theVideo = videos.unshift()
setMp4Source1(theVideo)
}
nextVideo() // start the chain here!
Now, this doesn't, as in your initial example, play a random video - just the next in the queue. You can play a random video and remove it from the queue by using splice() in nextVideo() as such:
function nextVideo() {
let randomIndex = Math.floor(Math.random() * videos.length)
let theVideo = videos[randomIndex]
videos.splice(randomIndex,1) // remove 1 element starting at the index
setMp4Source1(theVideo)
}
Of course, next you'll want to add a check to make sure you're not accessing an empty array...
function nextVideo() {
if( videos.length < 1) {
// no moar videos! :(
// probably best to bail out here and avoid further chaining.
// if you're clever, you'll add a placeholder image to let
// the user know there's no more videos.
// maybe something from http://placekitten.com/
player1.removeEventListener('ended', nextVideo, false)
sizer_x = player1.clientWidth
sizer_y = player1.clientHeight
const kitty = '<img src="http://placekitten.com/' + sizer_x + '/' + sizer_y + '"/>'
const kittyImg = document.createElement(kitty)
player1.parentNode.replaceChild(kittyImg, player1)
return
}
let randomIndex = Math.floor(Math.random() * videos.length)
let theVideo = videos[randomIndex]
videos.splice(randomIndex,1) // remove 1 element starting at the index
setMp4Source1(theVideo)
}
Keep track of the index numbers played with a Set object. Set object is simular to an array but will only contain unique items. Details are commented in the following Snippet.
const videos = [
"vs8s3.mp4", "vs12s3.mp4", "vs21s3.mp4", "vs2s3.mp4"
];
const player = document.querySelector("video");
// Create a Set object
const played = new Set();
function playVideo() {
let current = Math.floor(Math.random() * videos.length);
const base = 'https://glpjt.s3.amazonaws.com/so/av/';
const source = base + videos[current];
/* Check if video has already been played */
// If Set {played} DOES NOT have the {current} index number...
if (!played.has(current)) {
// Add {current} index number to Set {played}
played.add(current);
player.src = source;
player.play();
}
/* or if Set {played} does have {current} index number AND Set {played}
DOES NOT have the same amount of numbers as Array {videos}... */
else if (played.size != videos.length) {
// Run the function again
playVideo();
}
// Otherwise end function
else {
return false;
}
/* OPTIONAL: Display the indexes of each video played in order */
console.clear();
console.log(JSON.stringify(Array.from(played)));
};
player.addEventListener('ended', playVideo, false);
player.addEventListener('click', playVideo, false);
video {
cursor: pointer;
}
<video poster='http://simgbb.com/background/W46xw0TswdDx.jpg' width='360'></video>

How to load all images before the game starts? (JavaScript, Preloader)

I've designed this game, it's my first project. It's a spin-off from "The Pig Game" in a JavaScript course. I tweaked the HTML and CSS templates of the Pig Game for the UI, but I did the game design and coding from scratch. You can play the game here: https://jeffparadox.000webhostapp.com/
I've got some questions, if anyone cares:
What do you think, do you see any problems? Can anything be clearer (especially in terms of UI) than it is now?
Game works fast on my comp. But when I visit the site, images don't start spinning right away; it takes about 30 seconds to start seeing images spin visibly. I think it's because the browser is loading the images but the code runs faster. Is there a way to pre-load these images in the code, so the game starts properly? Or, if I clean up my code, will the game load faster without needing to pre-load the images?
Here's my JS code. If anyone's interested in checking it and telling me which parts I can clean-up and optimize, I'd really appreciate it. Thanks in advace:
"use strict";
// Selecting elements
const player0El = document.querySelector(".player--0");
const player1El = document.querySelector(".player--1");
const tries0El = document.getElementById("tries--0");
const tries1El = document.getElementById("tries--1");
const current0El = document.getElementById("current--0");
const current1El = document.getElementById("current--1");
const animalEl = document.querySelector(".animal");
const btnSpin = document.querySelector(".btn--spin");
const btnReset = document.querySelector(".btn--reset");
const btnRestart = document.querySelector(".btn--restart");
const youWin0El = document.querySelector("#you-win--0");
const youWin1El = document.querySelector("#you-win--1");
const highScore0El = document.querySelector(".high-score--0");
const highScore1El = document.querySelector(".high-score--1");
// Declare let variables
let triesLeft,
playerScores,
highScores,
activePlayer,
round,
currentScore,
playing;
// Starting conditions
const init = function () {
youWin0El.classList.add("hidden");
youWin1El.classList.add("hidden");
youWin1El.textContent = "You Win! 🎉";
youWin0El.textContent = "You Win! 🎉";
currentScore = 0;
triesLeft = [10, 10];
playerScores = [0, 0];
highScores = [0, 0];
activePlayer = 0;
round = 3;
playing = true;
btnRestart.textContent = `🕑 ROUND: ${round}`;
tries0El.textContent = 10;
tries1El.textContent = 10;
current0El.textContent = 0;
current1El.textContent = 0;
animalEl.src = "noAnimal.jpg";
player0El.classList.remove("player--winner");
player1El.classList.remove("player--winner");
player0El.classList.add("player--active");
player1El.classList.remove("player--active");
};
// Initialize game
init();
// ***GAME FUNCTIONS***
// Switch players
const switchPlayer = function () {
activePlayer = activePlayer === 0 ? 1 : 0;
player0El.classList.toggle("player--active");
player1El.classList.toggle("player--active");
};
// Check how many rounds left
const checkRound = function () {
btnRestart.textContent = `🕑 ROUND: ${round}`;
if (round < 1) {
gameOver();
} else if (triesLeft[activePlayer] < 1 && round > 0) {
if (triesLeft[0] === 0 && triesLeft[1] === 0) {
triesLeft[0] = 10;
triesLeft[1] = 10;
tries0El.textContent = 10;
tries1El.textContent = 10;
}
switchPlayer();
}
};
// End of game
const gameOver = function () {
playing = false;
if (playerScores[0] > playerScores[1]) {
youWin0El.classList.remove("hidden");
} else if (playerScores[0] < playerScores[1]) {
youWin1El.classList.remove("hidden");
} else if (playerScores[0] === playerScores[1]) {
youWin1El.textContent = "It's a Tie 😲";
youWin0El.textContent = "It's a Tie 😳";
youWin1El.classList.remove("hidden");
youWin0El.classList.remove("hidden");
}
};
// Check the rabbit, increase and log the score
const checkRabbit = function () {
if (imageNumber === 0) {
currentScore =
Number(document.getElementById(`current--${activePlayer}`).textContent) +
1;
playerScores[activePlayer] = currentScore;
document.getElementById(
`current--${activePlayer}`
).textContent = currentScore;
}
};
// Update tries left
const triesUpdate = function () {
triesLeft[activePlayer] -= 1;
document.getElementById(`tries--${activePlayer}`).textContent =
triesLeft[activePlayer];
};
// Update high scores
const registerHighScore = function () {
if (playerScores[activePlayer] > highScores[activePlayer]) {
highScores[activePlayer] = playerScores[activePlayer];
document.getElementById(
`high-score--${activePlayer}`
).textContent = `High Score: ${highScores[activePlayer]}`;
}
};
// ***GAME ENGINE***
// Declare game engine variables
let interval, imageNumber;
// Spinning images
btnSpin.addEventListener("click", function () {
if (playing) {
// Change button to Stop
btnSpin.textContent = `â›” STOP!`;
// Stop the spinning (Runs only when interval is declared)
if (interval) {
clearInterval(interval);
interval = null;
btnSpin.textContent = `🎰 SPIN!`;
triesUpdate();
checkRabbit();
registerHighScore();
if (triesLeft[0] < 1 && triesLeft[1] < 1) {
round -= 1;
}
checkRound();
// Start the spinning (Runs only when interval is null or undefined)
} else {
// Loop with time intervals
interval = setInterval(function () {
// Genarate image number
imageNumber = Math.trunc(Math.random() * 10);
// Show image with the generated number
animalEl.src = `animal-${imageNumber}.jpg`;
}, 5);
}
}
});
// ***RESET GAME***
btnReset.addEventListener("click", init);
You can preload images by putting this in your <head> for each image you use:
<link rel="preload" as="image" href="animal-1.png">
More documentation here: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
As for the other questions, they may be a better fit at SE Code Review: https://codereview.stackexchange.com/

Playing multiple fractions of HTML5 videos at a time

I am trying to write a function that will take an id of a div and play a given video from for example 2/10th of the way through to 3/10th of the way through and return an event so I can do something else.
I am not to clever with events as yet, and the video duration is not working out for me, any help appreciated. I have jQuery installed.
Some improvement since last time...
Updated, just need the listener to work next.
var finished_event = new Event('finished');
$(document).ready(function(){
class Player {
constructor(pos, vid, part, parts){
this.pos = pos;
this.vid = vid;
this.part = part;
this.parts = parts;
}
start(){
var it = this;
var html = '<video class="video-fit" controls>';
html += '<source src="';
html += it.vid;
html += '" type="video/mp4">';
html += '</video>';
$(it.pos).html(html);
var video = $(it.pos + ' video')[0];
video.addEventListener('loadeddata', function(){
var dur = video.duration;
var fra = dur / it.parts;
var beg = it.part * fra;
var end = it.part * (fra + 1);
video.currentTime = beg;
video.play();
video.addEventListener('timeupdate', function() {
if (video.currentTime >= end) {
video.pause();
this.dispatchEvent(finished_event);
}
}, false);
}, false);
return it;
}
}
$('body').click(function(){
let player_1 = new Player('#pos-1', 'videos/576p.mp4', 5, 10);
player_1.start();
let player_2 = new Player('#pos-2', 'videos/576p.mp4', 5, 10);
player_2.start();
let player_3 = new Player('#pos-3', 'videos/576p.mp4', 5, 10);
player_3.start();
let player_4 = new Player('#pos-4', 'videos/576p.mp4', 5, 10);
player_4.start();
//.addEventListener('finished', function(){ console.log('Finished'); }, false)
});
});
The timeupdate event fires a lot, so it could fire multiple times within the this.currentTime >= end check.
Not changing your code too much, you would want to set a playing state/var and on canplay event change timestamp and then play, this would, in turn, trigger a seeked event which then you can set the video as playing, then on timeupdate, check your timing plus is the video playing.. and for the last video you would need to check ended event as it won't enter into your check this.currentTime >= end as end is +1 second.
Then to separate the event functions from the Player class, id would use an array and watch it for changes, then by pushing a function to the array/stack you can then do a check within the function each time its invoked if the stack matches the video length, suppose you could do it other ways.
(function () {
let video =
'https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/twitter_cat.mp4';
let videos = [
{ id: '#pos-1', video, part: 1, parts: 10 },
{ id: '#pos-2', video, part: 2, parts: 10 },
{ id: '#pos-3', video, part: 3, parts: 10 },
{ id: '#pos-4', video, part: 4, parts: 10 },
];
const playqueue = [];
Object.defineProperty(playqueue, 'push', {
value: function (...args) {
var arr = Array.prototype.push.apply(this, args)
if (typeof args[0] === 'function') args[0]();
return arr;
}
});
function finished_event() {
if (playqueue.length === videos.length) {
console.log('Do something, all videos have stopped playing');
}
}
function video_finished_event(player) {
console.log(
'Do something, ' + JSON.stringify(player) + ' has stopped playing'
);
playqueue.push(finished_event);
}
class Player {
constructor(pos, vid, part, parts) {
this.pos = pos;
this.vid = vid;
this.part = part;
this.parts = parts;
}
start() {
var it = this;
var html = '<video class="video-fit" data-vid="' + it.pos + '" controls>';
html += '<source src="';
html += it.vid;
html += '" type="video/mp4">';
html += '</video>';
$(it.pos).html(html);
var video = $('[data-vid="' + it.pos + '"]')[0];
video.addEventListener(
'loadeddata',
function () {
var fra = video.duration / it.parts;
var beg = it.part * fra;
var end = it.part * (fra + 1);
video.addEventListener('canplay', function () {
if (!this.playing) {
this.currentTime = beg;
this.play();
}
});
video.addEventListener('seeked', function () {
this.playing = true;
});
video.addEventListener('timeupdate', function () {
if (this.playing && this.currentTime >= end) {
this.pause();
this.playing = false;
video_finished_event(it);
}
});
video.addEventListener('ended', function () {
if (this.playing) {
this.pause();
this.playing = false;
video_finished_event(it);
}
})
},
false
);
return it;
}
}
videos.forEach(video => {
video.player = new Player(video.id, video.video, video.part, video.parts);
video.player.start();
});
})();
.videos div {
display: inline-block;
width: calc(25vw - 15px);
height: 100%;
}
.videos div video {
width: 100%;
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="videos">
<div id="pos-1"></div>
<div id="pos-2"></div>
<div id="pos-3"></div>
<div id="pos-4"></div>
</div>
I suggest you to put an unique id on video, here i choose vpos-1/2/3/4/...
and i display video from beg to end:
var html = '<video ' + 'id="v' + it.pos + '" class="video-fit">';
html += '<source src="';
html += it.vid;
html += '" type="video/mp4">';
html += '</video>';
$(it.pos).html(html);
var video = document.getElementById('v' + it.pos);
$(video).bind('timeupdate', function() {
if(video.currentTime > end){
video.pause();
}
});
$(video).on('play', function() {
video.playbackRate = 1.0;
//calcul the value of beg
video.currentTime = beg;
video.play();//suppress if you have autoplay
});
$(video).bind('ended', function() {
// nothing yet
});
if you want to autoplay and/or display controls i suggest you to add
controls="controls" autoplay
to tag video
if you want to remove video: just do src=''
It stops the video and it saves the memory

How can I get an AudioBufferSourceNode's current time?

When working with audio elements (<audio>) or contexts(AudioContext), you can check their currentTime property to know exactly the play time of your buffer.
All of this is fine an dandy until I created multiple sources (or AudioBufferSourceNode) in a single AudioContext.
The sources could be played at different times, therefore I would need to know their corresponding currentTime's, to illustrate:
Some base code for you to work off:
buffer1 = [0,1,0]; //not real buffers
buffer2 = [1,0,1];
ctx = new AudioContext();
source1 = ctx.createBufferSourceNode();
source1.buffer = buffer1;
source1.connect(ctx.destination);
source1.start(0);
source2 = ctx.createBufferSourceNode();
source2.buffer = buffer2;
source2.connect(ctx.destination);
setTimeout(1000/*some time later*/){
source2.start(0);
}
setTimeout(1500/*some more time later*/){
getCurrentTime();
}
function getCurrentTime(){
/* magic */
/* more magic */
console.log("the sources currentTime values are obviously 1500 (source1) and 500 (source2).");
}
What I usually do is create a wrapper for the audio source node that keeps track of the playback state. I've tried to minimise the code below to show the basics.
The core idea is to keep track of the time the sound is started and the time the sound is 'paused' and use those values to get the current time and to resume playback from the paused position.
I put a working example on codepen
function createSound(buffer, context) {
var sourceNode = null,
startedAt = 0,
pausedAt = 0,
playing = false;
var play = function() {
var offset = pausedAt;
sourceNode = context.createBufferSource();
sourceNode.connect(context.destination);
sourceNode.buffer = buffer;
sourceNode.start(0, offset);
startedAt = context.currentTime - offset;
pausedAt = 0;
playing = true;
};
var pause = function() {
var elapsed = context.currentTime - startedAt;
stop();
pausedAt = elapsed;
};
var stop = function() {
if (sourceNode) {
sourceNode.disconnect();
sourceNode.stop(0);
sourceNode = null;
}
pausedAt = 0;
startedAt = 0;
playing = false;
};
var getPlaying = function() {
return playing;
};
var getCurrentTime = function() {
if(pausedAt) {
return pausedAt;
}
if(startedAt) {
return context.currentTime - startedAt;
}
return 0;
};
var getDuration = function() {
return buffer.duration;
};
return {
getCurrentTime: getCurrentTime,
getDuration: getDuration,
getPlaying: getPlaying,
play: play,
pause: pause,
stop: stop
};
}
Old thread (and very useful! thanks!) , but maybe worth mentioning that in the example above instead of
function update() {
window.requestAnimationFrame(update);
info.innerHTML = sound.getCurrentTime().toFixed(1) + '/' + sound.getDuration().toFixed(1);
}
update();
it may be more precise and less resource intensive to use a createScriptProcessor
like explained in this post
const audioBuffer = await audioContext.decodeAudioData(response.data);
const chan = audioBuffer.numberOfChannels;
const scriptNode = audioContext.createScriptProcessor(4096, chan, chan);
scriptNode.connect(audioContext.destination);
scriptNode.onaudioprocess = (e) => {
// ---> audio loop <----
};
[Update]
Note: As of the August 29 2014 Web Audio API spec publication, this feature has been marked as deprecated, and was replaced by AudioWorklet (see AudioWorkletNode). https://developers.google.com/web/updates/2017/12/audio-worklet

Categories

Resources