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:
- src: It is a string or an array of strings that specified path of the audio file. The array of strings can be used to specify multiple paths for the support of various browsers.
- callback: It is a callback function that would be fired when the ‘canplaythrough’ event fires. This event is fired when the audio has completed loading and does not require any additional buffering. It is an optional parameter.
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.zambiatek.com/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/createAudio
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!




