Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
HTML5 Audio to Play Randomly
HTML5 Audio API allows you to play audio files randomly by combining JavaScript arrays with the Math.random() method. This technique is useful for music players, games, or any application requiring random audio playback.
Setting Up the Audio Collection
First, initialize an array of audio sources. Each song should be added to the collection using the init() function:
init ([
'http://demo.com/songs/song1.mp3',
'http://demo.com/songs/song2.mp3',
'http://demo.com/songs/song3.mp3'
]);
Complete Random Audio Player Implementation
Here's a complete example that creates audio objects and implements random playback:
<!DOCTYPE html>
<html>
<head>
<title>Random Audio Player</title>
</head>
<body>
<button onclick="playRandom()">Play Random Song</button>
<button onclick="stopAudio()">Stop</button>
<p id="currentSong"></p>
<script>
let collection = [];
let currentAudio = null;
// Initialize audio collection
function init(songs) {
collection = songs.map(src => new Audio(src));
}
// Play random audio
function playRandom() {
if (currentAudio) {
currentAudio.pause();
currentAudio.currentTime = 0;
}
const randomIndex = Math.floor(Math.random() * collection.length);
currentAudio = collection[randomIndex];
currentAudio.play();
document.getElementById('currentSong').textContent =
`Playing song ${randomIndex + 1}`;
}
// Stop current audio
function stopAudio() {
if (currentAudio) {
currentAudio.pause();
currentAudio.currentTime = 0;
document.getElementById('currentSong').textContent = '';
}
}
// Initialize with sample audio files
init([
'https://www.soundjay.com/misc/sounds/bell-ringing-05.wav',
'https://www.soundjay.com/misc/sounds/fail-buzzer-02.wav',
'https://www.soundjay.com/misc/sounds/success-fanfare.wav'
]);
</script>
</body>
</html>
Random Selection Function
The core function uses Math.random() to select and play a random audio file from the collection:
function displayRandom() {
// Generate random index
const randomIndex = Math.floor(Math.random() * collection.length);
// Get the audio object at random index
const audio = collection[randomIndex];
// Play the selected audio
audio.play();
// Optional: Set up next random play after current song ends
setTimeout(() => {
displayRandom(); // Play next random song
}, audio.duration * 1000);
}
console.log("Random audio function ready");
Random audio function ready
How It Works
The random selection process involves three key steps:
-
Generate Random Number:
Math.random()creates a decimal between 0 and 1 -
Scale to Array Length: Multiply by
collection.lengthto get range 0 to array size -
Floor to Integer:
Math.floor()converts to valid array index
Enhanced Features
For a more robust random audio player, consider adding these features:
// Prevent same song playing twice in a row
function playRandomUnique() {
let randomIndex;
do {
randomIndex = Math.floor(Math.random() * collection.length);
} while (randomIndex === lastPlayedIndex && collection.length > 1);
lastPlayedIndex = randomIndex;
collection[randomIndex].play();
}
// Shuffle entire playlist
function shufflePlaylist() {
for (let i = collection.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[collection[i], collection[j]] = [collection[j], collection[i]];
}
}
Conclusion
HTML5 Audio with Math.random() provides an effective way to implement random audio playback. This approach works well for music players, sound effects, and interactive applications requiring unpredictable audio sequences.
