Skip to content

Instantly share code, notes, and snippets.

@TheCloudlessSky
Created September 7, 2012 14:06
Show Gist options
  • Save TheCloudlessSky/3666530 to your computer and use it in GitHub Desktop.
Save TheCloudlessSky/3666530 to your computer and use it in GitHub Desktop.
Playing Audio
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
function playRandomSong() {
var songs = [
'D:/Music/Dredg/Catch Without Arms/01 - Ode To The Sun.mp3',
'D:/Music/Dredg/Catch Without Arms/02 - Bug Eyes.mp3',
'D:/Music/Dredg/Catch Without Arms/03 - Catch Without Arms.mp3'
];
// Pick a random song.
var songIndex = Math.floor(Math.random() * songs.length);
$('#song-name').text('Playing ' + songs[songIndex]);
$('#song-source').prop('src', songs[songIndex]);
// Grab the actual <audio> element from the jQuery object.
var audio = $('#song-audio')[0];
// Just in case.
audio.pause();
// Load the audio into the buffer.
audio.load();
// Start the song.
audio.play();
}
// This little $(function() { ... }) tells jQuery to run
// this function when the page loads.
$(function() {
playRandomSong();
$('#song-audio').on('ended', function() {
playRandomSong();
});
$('#song-play-random').on('click', playRandomSong);
});
</script>
</head>
<body>
<h2 id="song-name"></h2>
<audio id="song-audio" controls>
<source id="song-source" />
<p>Audio not supported.</p>
</audio>
<br />
<button id="song-play-random">Random Song!</button>
</body>
</html>
@robertobarlocci
Copy link

Genius! Was exactly what i was searching for. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment