preface

National Day eight days to entertainment, teach you how to use code to write a piano 🎹, and it plays songs. Student if we have a QinJi like lang lang, presumably after the girls will be very easy, but in the past, a piano for ordinary families, consumption is very high, so we might as well write a belongs to own piano, ha ha, really piano sound, though less, but can write, it is quite a sense of accomplishment.

There is no need to use very complicated or difficult knowledge, as long as you follow the steps in the article step by step, you can finally do it. Action is better than action. Let’s get started.

The project’s Gitee address: gitee.com/Dream-Star/…

Draw a piano

First, we need to create the piano keys. Here, ul+ Li is used as the skeleton of the piano, where DIV represents the white key of the piano and P represents the black key of the piano.

<ul>
   <li><div></div><p></p></li>
   <li><div></div><p></p></li>
   <li><div></div></li>
   <li><div></div><p></p></li>
 <li><div></div><p></p></li>  <li><div></div><p></p></li>  <li><div></div></li>  <li><div></div></li>  </ul> Copy the code

Once we’ve written the skeleton we’re going to have to give it some style, at least to make the keys look more like a real piano.

/*------- piano part --------*/ ul{
  width:480px;
  height:360px;
  transform: translate(-50%, -50%);
 position: absolute;  top: 50%;  left: 50%;  }  li{  float:left;  list-style-type: none;  position: relative;  }  li>div{  height: 360px;  width: 60px; Background: rgba (255255255, 3); border: 1px solid;  border-color:rgba(0, 0, 0, .8);  border-bottom-left-radius : 8px;  border-bottom-right-radius: 8px;  box-sizing: border-box;  box-shadow: /*inset 3px 0 10px #c9c6c6,*/  inset 5px -8px 0 # 00000023;  text-align: center;  display:table-cell;  vertical-align: bottom;  }  li:not(:last-child)>div{  border-right: none;  }  li>div:hover{  background: rgb(255, 97, 97);   } /* The style when the white key is pressed */ .white_active{  box-shadow: inset 3px -2px 0 # 00000036; Background: linear - gradient (45 deg, rgba (255255255, 7), rgba (255255255, 5)); }   li>p{  height: 200px;  width: 40px;  background-color: # 000; Border - bottom - left - the radius: 5.5 px;Border - bottom - right - the radius: 5.5 px; box-shadow: inset 5px -7px 0 #2c2c2c;  position: absolute;  top:0;  left: 40px;  z-index: 999;  }  li>p:hover{  background: linear-gradient(45deg, #4c4c4c, #444444);  } /* The style when the black key is pressed */ .black_active{  box-shadow:inset 3px -5px 0 #2c2c2c;  } Copy the code

Now the piano is like this, the shape has been, but it is only a picture, we click the keys can not hear the sound.

Add sound to the piano

The piano has a picture, we will start to add sound, here to use JS, first introduce the sound source.

// Add audio to the pianofor (var i = 1; i <= 8; i++) {
  var addaudio = document.createElement("audio");
  addaudio.setAttribute("src"."audios/" + "w" + i + ".ogv");
  document.body.appendChild(addaudio);
} for (var i = 1; i <= 5; i++) {  var addaudio = document.createElement("audio");  addaudio.setAttribute("src"."audios/" + "b" + i + ".ogv");  document.body.appendChild(addaudio); } Copy the code

Now that the audio source is introduced, all we need to do is make the piano key press and play the corresponding audio. Here we can achieve two ways of playing the piano, one is to click the keys directly, the other is to play through our keyboard keys.

Use S~L keys on the keyboard to operate the piano white keys,E,R,Y,U,I to operate the piano black keys. We first get the relevant DOM using JS.

let audios = document.getElementsByTagName("audio"),
buttons = document.querySelectorAll("ul>li>div"),
blacks = document.querySelectorAll("ul>li>p");
Copy the code

① Click the keyboard with the mouse

Now that we have the dom of the key, we use the for loop to add the corresponding mouse events to the DOM of the key in sequence.

for (var i = 0; i < 8; i++) {
  buttons[i].index = i;
  buttons[i].onmousedown = function () {
    //alert(this.index);
    buttons[this.index].classList.add('white_active')
 audios[this.index].load();  audios[this.index].play();  };   buttons[i].onmouseup = function () {  buttons[this.index].classList.remove('white_active')  }; } for (var i = 0; i < 5; i++) {  blacks[i].index = i + 8;  blacks[i].onmousedown = function () {  //alert(this.index);  blacks[this.index-8].classList.add('black_active')  audios[this.index].load();  audios[this.index].play();  //alert(audios[this.index].src);  };   blacks[i].onmouseup = function () {  blacks[this.index-8].classList.remove('black_active')  }; } Copy the code

② The keyboard as a key

First we need to know the keyCode value of the key so that we can add events to the key. Once you know the key code for the key, place it in an array, and then use a for loop to add an event to each key.

// Operate the white keys of the piano to make soundvar keyCodes = new Array(83, 68, 70, 71, 72, 74, 75, 76, 69, 82, 89, 85, 73);
document.body.onkeydown = function (e) {
  for (var i = 0; i < keyCodes.length; i++) {
    if (e.keyCode == keyCodes[i]) {
 if (i < 8) {  buttons[i].classList.add('white_active');  } else {  blacks[i-8].classList.add('black_active');  }  audios[i].load();  audios[i].play();  }  } };  // Operate the black keys of the piano to make sounddocument.body.onkeyup = function (e) {  //document.title=e.keyCode;  for (var i = 0; i < keyCodes.length; i++) {  if (e.keyCode == keyCodes[i]) {  if (i < 8) {  buttons[i].classList.remove('white_active');  } else {  blacks[i-8].classList.remove('black_active');  }  }  } }; Copy the code

At this point our piano is ready to play.

Add the library

Light piano without music how line, we can find a music score on the Internet, and then add to the corresponding place is ok.

Write out the layout first, so you don’t have to add fancy styling here.

<div>
Please enter simplified spectrum:   <input type="text" id="song" placeholder="Please enter a song name">
   <button id="check"> confirm < / button >  </div>
Copy the code

Then start to write the logical part, scROE object is used to store the song information, do not want to go to the Internet to find the song information, you can directly copy the last part of the simplified music. The format is similar to {‘ song name ‘:’ Lyrics and notation ‘}, where template strings can be used.

var scroe = {};

var numReg = /[1-9]/g;
var wordReg = /[\u4e00-\u9fa5]+/g;

 var str; var shows; var words; var wordsIndex; var wordsCurrent; var current;   function play() { buttons.forEach((el)=>el.classList.remove('show'))  var songName = song.value;   if(songName === ' ') { return alert('Please enter a song name')  }   if(scroe.hasOwnProperty(songName)){  str = scroe[songName];  shows = str.match(numReg);  words = str.match(wordReg);  wordsIndex = 0;  wordsCurrent = 0;  current = 0;  console.log(songName)  buttons[shows[0]/1 - 1].classList.add('show');  text.textContent = words[0]  }else{  return alert('The name of the song you entered has not been added to the library')  } }  check.addEventListener('click',play) Copy the code

Now the effect graph is below this appearance 👇.

Add lyrics and key prompts

The top part of the layout is already written, so start writing the logic directly.

function start() {// Display the lyrics  if(wordsCurrent>=words[wordsIndex].length-1){
    wordsCurrent = 0;
    wordsIndex++;
 text.textContent = words[wordsIndex]  }else{  wordsCurrent++  }    if(current === shows.length-1){  buttons[shows[shows.length-1]/1 - 1].classList.remove('show');  return console.log('End of play',current)  }   var showButton = shows[current+1]/1 - 1;  var hiddenButton = shows[current]/1 - 1;   buttons[hiddenButton].classList.remove('show');  buttons[showButton].classList.add('show');  current++ } Copy the code

Then add this code to the corresponding keystroke events and mouse click events.

i == shows[current]-1 ? start() : ' ';
Copy the code

Now we have basically achieved what we want.


Add a little decoration

We can number the keys so that we can play them.

// Add numbers to the keysbuttons.forEach((el,index)=>el.textContent = index+1)

window.addEventListener('keydown'.function(e){
  if(e.keyCode == 86){
 if(buttons[0].textContent ! =' ') { buttons.forEach((el)=>el.textContent = ' ')  }else{  buttons.forEach((el,index)=>el.textContent = index+1)  }  } }) Copy the code

At this point, the keys have a corresponding number. We can also use the shortcut key V to show and hide the number of the switch.Let’s add instructions to the piano.

let x = document.getElementById("btn-js"),
y = document.getElementById("js"),

// Hide and show introductionsfunction hide() {
 y.style.display === "block" ? y.style.display = "none" : y.style.display = "block" }  x.addEventListener('click',hide); Copy the code

You can see that the lyrics are displayed while the song is being played.

Now a simple version of the piano has been made, the appearance is not very similar to the real piano. Use it to play a song 😀.

Share a brief score of some songs

A sunny day

3243 157 1751-166 655 543 2343

I tried to hold your hand on a windy day but it was raining hard and I couldn’t see you

3453 457 2711-115 5654 2345 61 6 77

How much longer can I stay with you till it clears up maybe I’ll be better

3243 157 1751-166 655 543 2343

Once upon a time, there was someone who loved you for a long time, but the wind gradually blows away the distance

3453 457 2711-115 5654 6712 32 11

I finally get one more day of love but at the end of the story you say goodbye

The Longest movie

12433 345431 12433 321622

We started with a very long movie that ran for three years and I still had tickets

12433 345431 431 32211 [45]

The ballet on ice is still spinning in my mind watching you slowly forget you

12433 345431 12433 321622

Hazy time we slip far skate draw circle up who changed

1 [21] 433, 34543112, 4431, 432171

If again to will not slightly distressed love is not open to precious

321622 32152211 321622 14321 543323

Just give me two more minutes to freeze the memory don’t melt the tears How am I supposed to remember when you’re wearing makeup

34363322 23252272 53411 243211

Remember you told me to forget remember you told me to forget you said you would cry not because of care

Sit at the same table of you

55553457-6666465.

Tomorrow will you remember the diary you wrote yesterday

55557654-4444321.

Tomorrow, do you still remember you who used to cry most

55553457-6666465.

The teachers can’t remember you who can’t guess the problem

55557654-4444321.

I also accidentally turned over the photo to think of your deskmate

111156113-2222176.

Who married the sentimental you who read your diary

77777125-7712171.

Who put up your long hair who made your wedding clothes

🏆 nuggets technical essay | double festival special articles