Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!