Open In App

p5.js MediaElement onended() Method

Last Updated : 29 Sep, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The onended() method of p5.MediaElement of p5.js library is used to schedule the given function that will be called whenever the audio or video ends. This callback will not be called if the media element is looping. This media element is passed as the argument to the callback.

Syntax:

onended( callback )

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

  • callback: It is a function that specifies the callback function when the media has ended.

The following libraries are included in the “head” section of the HTML file for the JavaScript functions to work.

<script src=”p5.Image.js”></script>
<script src=”p5.min.js”></script>

The example below illustrates the onended() method in p5.js library

Example:

Javascript




function setup() {
    createCanvas(550, 300);
    textSize(18);
  
    text("The onended() function would " +
         "be called when the video ends",
         20, 20);
  
    example_media =
      createVideo("sample-video.mp4");
    example_media.size(300, 150);
    example_media.position(20, 60);
  
    playBtn = createButton("Play Button");
    playBtn.position(30, 220);
    playBtn.mousePressed(() => {
  
      example_media.play();
    });
  
    // Using the onended() method
    example_media.onended(onendedShow);
}
  
function onendedShow(mediaElem) {
  
  // Get the media element from the callback
  let mediaSource = mediaElem.src;
  
  text("The media has ended playback!",
       20, 260);
  text("The source of the video is: " +
       mediaSource, 20, 280);
}


Output:

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads