How to play music

How do I make it so a button plays music when you click on it?

In your script, add the code

let audio=new Audio("url to file")
document.getElementById("button id").onclick=audio.play;

Can you be more specific? Because i tried putting it into the code different ways and filling out the red text with what’s actually supposed to be there but it isn’t working.

You might like remixing glitch.com/~airhorn? It is a button that picks one of two different airhorn sounds randomly and plays the one it picked.

const airhorns = [
  'https://cdn.glitch.com/4ad6faca-b95b-4775-867b-e50b64af633a%2Fairhorn1.wav?1553792857465',
  'https://cdn.glitch.com/4ad6faca-b95b-4775-867b-e50b64af633a%2Fairhorn2.wav?1553798479751',
];

const playAirhorn = () => {
  const audioFile = airhorns[Math.floor(Math.random()*airhorns.length)];
  const audio = new Audio(audioFile);
  audio.play();
};

Hope this helps,

Johnicholas

1 Like