How to create a program to loop through videos in p5.js?

Member

by dana , in category: Javascript , 2 months ago

How to create a program to loop through videos in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 2 months ago

@dana 

To create a program that loops through videos in p5.js, you can follow these steps:


Step 1: Include the p5.js library in your HTML file by adding the following line in the head section of your HTML file:

1
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>


Step 2: Create a new p5.js sketch file and define a setup function to create a canvas and preload function to load the videos. Here is an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
let videos = [];
let currentVideoIndex = 0;

function setup() {
  createCanvas(640, 480);
  videos.push(createVideo('video1.mp4'));
  videos.push(createVideo('video2.mp4'));
  videos.push(createVideo('video3.mp4'));
  
  videos[currentVideoIndex].play();
}

function preload(){
  for(let i=0; i<videos.length; i++){
    videos[i].hide();
  }
}


Step 3: Create a draw function that displays the current video and advances to the next video in the array when the current video ends. Here is an example code snippet:

1
2
3
4
5
6
7
8
9
function draw() {
  background(0);
  image(videos[currentVideoIndex], 0, 0, width, height);
  
  if (videos[currentVideoIndex].time() == videos[currentVideoIndex].duration()) {
    currentVideoIndex = (currentVideoIndex + 1) % videos.length;
    videos[currentVideoIndex].play();
  }
}


Step 4: Run the sketch by opening the HTML file in a web browser. The program will loop through the videos in the order they are defined in the videos array.


This is a simple example of how to create a program to loop through videos in p5.js. You can customize the program further by adding controls to pause or skip videos, or by adding effects to the videos as they are displayed.