p5.js | onended() Function

The onended() function is an inbuilt function in p5.js library. This function is used to schedule an event when the sound file reaches the end means if you are playing the audio you can schedule any event when that audio will reach the end of its duration. Be careful while using a loop with this function then the event that was scheduled will not trigger.

onended(callback)


Note:
All the sound-related functions only work when the sound library is included in the head section of the index.html file.

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

  • callback: This parameter is the name of the function that will be called when the audio reaches at the end of the buffer.

Below examples illustrate the p5.onended() function in JavaScript:
Example 1: In this example the audio will be played without loop.

filter_none

edit
close

play_arrow

link
brightness_4
code

var sound;
  
function setup() {
  
    // Initialize sound 
    sound = createAudio('pfivesound.mp3');
     
    // Playing the sound 
    sound.play();
  
    // event define after end of audio
    sound.onended(geeks);
  
  }
    
  //event that will occur 
  function geeks(dur) {
    alert('Audio ended ');
  }
   

chevron_right


Output: After finishing the audio.



Example 2: In this example the audio will be played with loop. So there will be no events.

filter_none

edit
close

play_arrow

link
brightness_4
code

var sound;
  
function setup() {
  
     // Initialize sound 
    sound = createAudio('pfivesound.mp3');
      
    // Playing the sound 
    sound.play();
  
    // looping the sound 
    sound.loop();
  
    // event define after end of audio
    sound.onended(geeks);
  }
    
  function geeks(dur) {
    alert('Audio ended ');
  }
   

chevron_right


Output:

No event will occur

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

Supported Browsers: The browsers supported by p5.js onended() function are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Safari
  • Opera

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.