Submodule 18.2: Video in p5.js
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
- Open your Visual Studio editor and the
p5yourName
folder. - Open the file
ex812.js
in your editor and save it asex1021.js
- Open the file
ex812.html
in your editor and save it asex1021.html
- In the
ex1021.html
file, update the link toex1021.js
from exersice812.js - Go to the
index.html
file and create, underModule 10
, alink
to theex1021.html
file with the title "Insert video".
Modify the ex1021.js
file and use as a base the above example to create a video which will automatically replay. You can see here an example.
// 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".
- See more about the createVideo() function
- See more about the loop() function