Home > Enterprise >  How do I make my button play a new audio file when I press it again?
How do I make my button play a new audio file when I press it again?

Time:12-10

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];

CodePudding user response:

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.
  • Related