Play son using html and javascript with an audio file array

Asked

Viewed 230 times

-3

I want to create a project to make a kind of game for me to study music. I would play a chord and I would reply what grade it would be. The system would give me the answer whether I got it right or not. This is to train my ear. So I’m starting with the first steps, but I can’t point to a file name in the array.

  • index.html:
  <!DOCTYPE html>    
  <html>    
  <head>    
  <meta charset="ISO-8859-1">    
  <title>    
  OUVIDO ABSOLUTO    
  </title>    
  <script src='/scripts/sons.js'></script>    
  </head>    
  <body>    

  <br><br>    

  <audio id="audio"></audio>    

  <form>    
  <label form="tocar">    
  <input type="button" value="tocar" onclick="tocar()">    
  </label>    
  </form>    
  </body>    
  </html>    
  • scripts/sons.js:
  lista_acordes=["C.wav", "D.wav", "E.wav"];     

  function tocar() {    
  var son = document.getElementById("audio");     
  son.src=lista_acordes[1];     
  son.play();     
  }    
  • I don’t think the question is duplicate, nor even appear. A question is about how to call an external file, and this is how to assign a value to an Html attribute by Javascript.

  • @Leandrade You’re right. I read both and they looked the same to me. I’ve reopened. ;)

  • No problem @Sam :) the community is always to help, we go!

  • Andre seems to me that you missed just one src on the tag audio, because when you do it in Javascript son.src=lista_acordes[1]; son which is the variable name for the audio tag does not have the src attribute yet.

1 answer

1


Good André, I don’t understand very well how the flow of playing the audio will be when you click the button, but if you want to assign a src the tag audio through a Javascript array, you just missed placing the empty attribute in html:

lista_acordes = ["C.wav", "D.wav", "E.wav"];

function tocar() {
  var som = document.getElementById("audio");
  som.src = lista_acordes[1];
  som.play();
  console.log(som);
}
<audio id="audio" src=""></audio>

<form>
  <label form="tocar">    
  <input type="button" value="tocar" onclick="tocar()">    
  </label>
</form>

  • the ringing flow will be defined as follows: a function I will create will return a random number between 0 and the size of the array-1. There will be more functions to validate whether you got it right or wrong and the name of the note played. Just remembering that I’m playing a little music game to practice my ear. I keep doing and testing and when it hangs at some point, so I posted two questions about the same project.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.