Playing audio files using JS and HTML, experimentations based on JavaScript30 Day 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Key template --> | |
<script type='text/html' id='key-template'> | |
<kbd>{{ key.key }}</kbd> | |
<span class='sound'>{{ key.name }}</span> | |
<audio src="sounds/{{ key.name }}.wav"></audio> | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var keyTemplate = document.querySelector( '#key-template' ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var keys = [ | |
{ | |
key: 'Q', | |
name: 'Blurp', | |
code: 81, | |
}, | |
{ | |
key: 'W', | |
name: 'Reow', | |
code: 87, | |
}, | |
{ | |
key: 'E', | |
name: 'Slippery', | |
code: 69, | |
}, | |
// ... etc | |
]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Key binding method | |
* | |
* Expects to be called via `Key.call()` on items from `keys` array | |
*/ | |
var Key = function() { | |
var key = this; | |
/** | |
* Create the DOM element from the template | |
*/ | |
key.element = document.createElement('div'); | |
key.element.classList.add('key'); | |
// replace the template tags with the data for this key | |
key.element.innerHTML = keyTemplate.innerHTML.replace( | |
/{{ key\.(key|name|code) }}/g, | |
( fullMatch, match ) => key[ match ] | |
); | |
// ... etc ... | |
// the audio element for this key | |
key.audio = key.element.querySelector('audio'); | |
// play the sound file associated with this key | |
key.play = function () { | |
// ... etc ... | |
} | |
} // end: Key() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Call the Key binding function on all of our keys | |
keys.forEach( key => Key.call( key ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment