Skip to content

Commit

Permalink
feat: ✨ play sound
Browse files Browse the repository at this point in the history
Start and stop playing some sound.
  • Loading branch information
simonberner committed Mar 14, 2024
1 parent 44a73fb commit 0a078c0
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion src/sketch.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,24 @@ let columns;
let rows;
let initialUniverse;
let resolution = 10;
let birdsong;
let playButton;

/**
* Initializes the canvas and sets up the initial state of the universe.
* Preload function is used to preload any necessary assets before the setup() is called. It is called once.
* In this case, it loads a birdsong audio file.
* (https://p5js.org/reference/#/p5/preload)
*
* @function preload
* @returns {undefined}
*/
function preload() {
birdsong = loadSound('assets/birdsong.mp3');
}

/**
* Initializes the canvas and sets up the initial state of the universe. It is called once.
* (https://p5js.org/reference/#/p5/setup)
*
* @function setup
* @returns {undefined}
Expand All @@ -16,6 +31,16 @@ function setup() {
columns = width
rows = height
initialUniverse = makeRandom2DArray(rows, columns)

// draw and position the button
playButton = createButton('Start/Stop sound');
playButton.position(0, 500);

// call playSound when play button clicked
playButton.mousePressed(playSound);

// set playback mode to 'restart'
birdsong.playMode('restart');
}

/**
Expand All @@ -25,6 +50,7 @@ function setup() {
* Right after the setup function, the draw function is called continuously until the program is stopped or noLoop() is called.
* The draw function is refreshed according to the frame rate (defined by the frameRate() function,
* 60 FPS by default).
* (https://p5js.org/reference/#/p5/draw)
*
* @returns {void}
*/
Expand All @@ -47,5 +73,15 @@ function draw() {
initialUniverse = calcNextGen(initialUniverse);
}

function playSound() {
if (birdsong.isPlaying()) {
birdsong.stop()
} else {
birdsong.play();
}
}

// Assigning the functions to the global window object.
window.setup = setup;
window.draw = draw;
window.preload = preload;

0 comments on commit 0a078c0

Please sign in to comment.