Geek Logbook

Tech sea log book

50projectsIn50days – Day 9: Sound Board

A sound board that has buttons with different sounds. If you click, you’ll hear a sound. The projects uses the <audio> element.

The <audio> HTML element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the <source> element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a MediaStream.

Mozilla Documentation

However, in the case of this demo we don’t use the controls attribute because the sound is inside a button element. The events we’re going to use are the play, and the pause event.

It’s interesting to note that the buttons are generated by an Array. But you need to add it in html. The play and pause events don’t have much to explain. There is an event listener ‘click’ which play the sound

sounds.forEach(sound => {
    const btn = document.createElement('button')
    btn.classList.add('btn')

    btn.innerText = sound

    btn.addEventListener('click', () => {
        stopSongs()

        document.getElementById(sound).play()
    })

    document.getElementById('buttons').appendChild(btn)
})

A stop function is created because we don’t have a native stop function. We are using instead the pause event:

function stopSongs() {
    sounds.forEach(sound => {
        const song = document.getElementById(sound)
        song.pause()
        song.currentTime = 0;
    })
}

You can see the code in this GitHub Repository: 09.sound_board and the demo of the project is here: Sound Board

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>