of course, why don't you also ask me to print "hello world" or ask me to do your programming homework.
HOW SHARMELESS TO ASK ME SOMETHING LIKE THAT, anyway, here it is:
-
Create a folder that will be the root directory of this musical nonsense.
-
You must be able to record or get an audio file for each musical note that you are going to use and put said files in a folder called notes, in this case there will be 12: A, Ab, B, Bb, C, D, Db, E, Eb, F, G, Gb.
2.1 make sure that notes folder is into the root directory
- in the root directory create an index.html file and paste this code:
- same as the index file create styles.css and paste this:
*, *::before, *::after {
box-sizing: border-box;
}
body {
background-color: #143F6B;
margin: 0;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.piano {
display: flex;
}
.key {
height: calc(var(--width) * 4);
width: var(--width);
}
.white {
--width: 100px;
background-color: white;
border: 1px solid #333;
}
.white.active {
background-color: #CCC;
}
.black {
--width: 60px;
background-color: black;
margin-left: calc(var(--width) / -2);
margin-right: calc(var(--width) / -2);
z-index: 2;
}
.black.active {
background-color: #333;
}
- now the javscript file, you know what to do:
const WHITE_KEYS = ['z', 'x', 'c', 'v', 'b', 'n', 'm']
const BLACK_KEYS = ['s', 'd', 'g', 'h', 'j']
const keys = document.querySelectorAll('.key')
const whiteKeys = document.querySelectorAll('.key.white')
const blackKeys = document.querySelectorAll('.key.black')
keys.forEach(key => {
key.addEventListener('click', () => playNote(key))
})
document.addEventListener('keydown', e => {
if (e.repeat) return
const key = e.key
const whiteKeyIndex = WHITE_KEYS.indexOf(key)
const blackKeyIndex = BLACK_KEYS.indexOf(key)
if (whiteKeyIndex > -1) playNote(whiteKeys[whiteKeyIndex])
if (blackKeyIndex > -1) playNote(blackKeys[blackKeyIndex])
})
function playNote(key) {
const noteAudio = document.getElementById(key.dataset.note)
noteAudio.currentTime = 0
noteAudio.play()
key.classList.add('active')
noteAudio.addEventListener('ended', () => {
key.classList.remove('active')
})
}
-
make sure the note names and note files are the same as yours in the notes folder.
-
blame yourself for threaten me to do something so dirty and inferior like this.
-
enjoy :)