Florian Pop mini project no. 9
How it works
The audio is added to the HTML using an <audio>
tag for each sound file with an id of the file name without the extension:
<audio loop id="pro-blend-1" src="/audio/pro-blend-1.wav"></audio>
Since <audio>
controls are not set nothing is visible on the page.
The JavaScript
An array called sounds
is created with name of each audio file without it’s extention.
A forEach
array method is used on this array which does the following:
- Creates a button for each item in the array
- Adds a class name of
btn
to each of these new buttons. - Adds these buttons to the DOM, in this case to a
<section>
element with an id ofaudio-buttons
. - Adds text from the array to each button:
btn.innerText = sound;
- Adds an event listener with arrow function to each button. The function grabs each button using
getElementById(sound)
and adds.play()
Finally a new function is created (outside of the above forEach
loop). The role of this function is pause any playing sounds when a new sound (button) is started. This function is called in the first event listener before the This may or may not be what you want.
The play()
and pause()
methods
The play()
and pause()
methods are part of the HTML5 audio and video DOM methods. They’re very simple taking no parameters and returning no values. They simply start playing or pause video or audio files.
Mark 2 version?
The following feautures could be added to another version.
- a way to make each button a toggle to turn each sound on or off.
- make each sound loop at preset times so all sounds repeat with the same rhythm. You can turn each sound to a loop using the
loop
attribute but then the sounds wouldn’t be in syncronicity. - toggle a class of active to style buttons that are playing.
- make the buttons responsive to keyboard buttons.