I'm making scene with a radio-like object, and I'd like to make it play a random audio file from my assets when is clicked. This question help me a lot to understand how to add the audio files Play sound on click in A-Frame but I can't figure out the random aspect. Thank you very much.
Asked
Active
Viewed 202 times
1 Answers
1
You can have an array of sound elements
// use ID's - grab by document.getElementById(audioIds[num])
var audioIds = ['one', 'two', 'three']
// use a class - grab by audioEls[num]
var audioEls = document.getElementsByClassName('sharedClassName')
and use a simple random to select an item
// get a random number between 0 and the number of the elements
let lastIndex = audioEls.length - 1 // arrays begin at 0.
var audioEl = audioEls[Math.round(Math.random() * lastIndex)]
Then on click
stop any playing sound, and grab a new one:
this.el.addEventListener('click', () => {
if (!playing) {
audioEl = audio[Math.round(Math.random() * (audio.length - 1))]
audioEl.play();
} else {
audioEl.pause();
audioEl.currentTime = 0;
}
playing = !playing;
});
You can check it out in my fiddle.

Piotr Adam Milewski
- 14,150
- 3
- 21
- 42
-
Thank you very much, Piotr! – Marcos Alfonzo Dec 20 '18 at 23:00
-
Dear Piotr, could it be possible that this solution in ment to handle only two audio assets? I've tried to adjust the values to my scene ("(audio.length - 4)", as I have five audio assets) but the component only plays randomly the first two.Sorry for the noob question and thank you again! – Marcos Alfonzo Dec 21 '18 at 14:19
-
@MarcosAlfonzo Sorry, i've made a mistake and used some c++ magic with the Random % number. There should be Random * number since js `Math.random` returns a number between [0, 1). I've updated the anwser and the fiddle to have 4 audio elements – Piotr Adam Milewski Dec 21 '18 at 14:35
-
Thank you very much for continuing to think about the problem! – Marcos Alfonzo Dec 21 '18 at 15:37
-
@MarcosAlfonzo no problem, sorry for the mistake, happy coding :) – Piotr Adam Milewski Dec 21 '18 at 15:39