Open In App

p5.MediaElement time() Method

The time() method of p5.MediaElement in p5.js is used to set or return the current time of the media element. It accepts a single parameter that denotes the time in seconds that the media should jump or skip to. The current time of the media can be returned by not passing any parameter to the function.

Syntax:



time( time )

Parameters: This method accepts a single parameter as mentioned above and described below:

Return Value: This method returns a Number that denotes the current time of the media element.



The example below illustrates the time() method in p5.js:

Example: 




function setup() {
    createCanvas(500, 400);
    textSize(18);
  
    text("Click on the buttons to skip " +
         "the video forward or backward",
         20, 20);
  
    example_media =
      createVideo("sample-video.mp4");
    example_media.size(500, 300);
    example_media.position(20, 100);
    example_media.showControls();
  
    skipbwdBtn =
      createButton("Skip Back 2 Seconds");
    skipbwdBtn.position(30, 40);
    skipbwdBtn.mousePressed(skipBackward);
  
    skipfwdBtn =
      createButton("Skip Forward 2 Seconds");
    skipfwdBtn.position(200, 40);
    skipfwdBtn.mousePressed(skipForward);
}
  
function skipForward() {
  clear();
  
  // Get the current time
  let currTime = example_media.time();
  
  // Add 2 seconds to skip forward
  let fwdTime = currTime + 2;
  
  // Set the new time that is two seconds
  // after the current time
  example_media.time(fwdTime);
  
  text("The video has been skipped forward",
       20, 80);
  
  text("Click on the buttons to skip "
       "the video forward or backward",
       20, 20);
}
  
function skipBackward() {
  clear();
  
  // Get the current time
  let currTime = example_media.time();
  
  // Subtract 2 seconds to skip back
  let fwdTime = currTime - 2;
  
  // Set the new time that is two seconds
  // before the current time
  example_media.time(fwdTime);
  
  text("The video has been skipped back",
       20, 80);
  
  text("Click on the buttons to skip " +
       "the video forward or backward",
       20, 20);
}

Output:

Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/amp/
Reference: https://p5js.org/reference/#/p5.MediaElement/time


Article Tags :