Open In App

p5.js createAudio() Function

The createAudio() function is used to create an audio element in the DOM. The audio is created as a p5.MediaElement, which has methods for controlling the media and its playback.

Syntax:



createAudio(src, callback)

Parameters: This function accept two parameters as mentioned above and described below:

Return Value: It returns a pointer to the p5.MediaElement with the audio.



Below examples illustrate the createAudio() function in p5.js:

Example 1:




function setup() {
  createCanvas(300, 300);
  text("Click on the buttons below to"
       "play/pause the audio", 20, 20);
   
  audioElement = createAudio("sample_audio.wav");
  audioElement.position(20, 50);
  audioElement.size(300);
   
  // Show the audio controls
  audioElement.showControls();
}

Output:

Example 2:




function setup() {
  createCanvas(300, 300);
  text("Loading the audio...", 20, 20);
  
  audioElement = createAudio("sample_audio.mp3", afterLoad);
  audioElement.position(20, 20);
  audioElement.size(300);
  
  playBtn = createButton("Play Audio");
  playBtn.position(30, 80);
  playBtn.mouseClicked(playAudio);
  
  pauseBtn = createButton("Pause Audio");
  pauseBtn.position(150, 80);
  pauseBtn.mouseClicked(pauseAudio);
}
  
function afterLoad() {
  text("The audio has finished loading and"+
              " can now be played!", 20, 40);
}
  
function playAudio() {
  audioElement.play();
}
  
function pauseAudio() {
  audioElement.pause();
}

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/createAudio


Article Tags :