Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

231
Vistas
How do I make my button play a new audio file when I press it again?

I've made a website on neocities that plays an audio file whenever you press the button GENERATE AUDIO

The funny thing is, it plays the same audio whenever I press it again. The only way to get a new audio is by reloading the page itself. Is there a way I can make the audio file change without having to reload the page?

here's my button:

<a href="#" onclick="test.play()"> GENERATE MUSIC </a>

and here's how I get it to play random audios from an array:

const audioList = [
     "audio1.mp3", 
     "audio2.mp3", 
     "audio3.mp3", 
     "audio4.mp3"];

var test = new Audio();
var audioNum = Math.floor(Math.random() * audioList.length);
test.src = audioList[audioNum];
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try this:

const audioList = [
  "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3",
  "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3",
  "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3",
  "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3"
];

const audio = new Audio()

function generateMusic() {
  const audioNum = Math.floor(Math.random() * audioList.length);
  audio.src = audioList[audioNum];
  audio.load()
  audio.play()
}
<a href="#" onclick="generateMusic()"> GENERATE MUSIC </a>

What I changed on your code:

  • Create a function which will pick a new song each time you press the button.
  • Set this song as .src and .play() it.
  • The load() method re-loads the audio element.
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda