<!doctype html>
<html>
<head>
<title>PlayAudio</title>
</head>
<body>
<script>
function playAudio() {
var audio = document.getElementById("MySound");
audio.play();
}
</script>
<input type="button" value="Play Audio" onclick="playAudio()">
<audio id="MySound" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio>
</body>
</html>
Solution 1 :
Solution 2 :
Suppose you have a project with files like this:
Project files
Then you can do in your HTML & JS code like this to make the sound played randomly when the submit button is clicked:
//Load the sound files into an array
const audioArr = [
new Audio('audio/audio1.ogg'),
new Audio('audio/audio2.ogg'),
new Audio('audio/audio3.ogg'),
new Audio('audio/audio4.ogg'),
new Audio('audio/audio5.ogg'),
new Audio('audio/audio6.ogg')
];
function playRandomAudio(){
//Get a random index of the sound to be played
const randomAudioIndex = Math.floor(Math.random() * (audioArr.length+1));
//Play the selected sound
audioArr[randomAudioIndex].play();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<input type="submit" value="Submit" onclick="playRandomAudio()">
<script src="test_sound.js"></script>
</body>
</html>
Hope this answers your question.
Problem :
I want to create a submit button, when every time you click it, it plays a random audio file.
Is there a fast way to do this with HTML/JS?
Comments
Comment posted by HelloWorld
Thanks but this is just to play 1 sound right, not a random sound from a list?
Comment posted by HelloWorld
Thanks I’ve tested this but only seems to play the first audio file, any ideas?