Submodule 18.2: Video in p5.js

  • Insert video
  • play with video
  • createCapture()

Insert video

In order to insert a video in p5.js we use the function createVideo()  . Inside this function we put the path to the video file.

We can combine videos with event controls to play/pause the video.

Example 

Here is an example code which shows a video together with a control button:

// set let playing to be false in the beginning
let playing = false;
let myVideo;
let myButton;


function setup() {
  // display the video
  myVideo = createVideo(['videos/Star.mp4']);
  myButton = createButton('play');
  // when button is pressed call the PausePlay function
  myButton.mousePressed(PausePlay);
}

// play or pause video
function PausePlay() {
  // if playing is true
  if (playing) {
    // make the video pause
    myVideo.pause()
    playing = false;
  }
  // else let the video play
  else {
    myVideo.play();
    playing = true;
  }

}

You can see the result of the above code here

Exercise

  1. Open your Visual Studio editor and the p5yourName folder.
  2. Open the file ex812.js in your editor and save it as ex1021.js
  3. Open the file ex812.html in your editor and save it as ex1021.html
  4. In the ex1021.html file, update the link to ex1021.js  from exersice812.js
  5. Go to the index.html file and create, under Module 10, a link to the ex1021.html  file with the title "Insert video".

Modify the ex1021.jsfile and use as a base the above example to create a video which will automatically replay. You can see here an example.

Answer:

// set let playing to be false in the beginning
let playing = false;
let myVideo;
let myButton;


function setup() {
  // display the video
  myVideo = createVideo(['videos/Star.mp4']);
  myButton = createButton('play');
  // when button is pressed call the PausePlay function
  myButton.mousePressed(PausePlay);
}

// play or pause video
function PausePlay() {
  // if playing is true
  if (playing) {
    // make the video pause
    myVideo.pause();
    playing = false;
  }
  // else let the video play
  //use loop to make it replay
  else {
    myVideo.loop();
    playing = true;
  }

}

Do a Git commit with the message "Insert video".