samedi 28 avril 2018

Javascript: play a random song from an array (list)

I want to play a random song in a website. The tunes are short (max a few seconds, they don't need preload or buffering).

This part works, the number of songs may be unlimited, because tunes.length automatically counts all songs.

document.write displays the URL of a random song URL on the screen

tunes = new Array(
'"http://example.net/abcd.ogg"',
'"http://example.net/efgh.ogg"',
'"http://example.net/ijkl.ogg"'
)
var audiopath = (tunes[Math.floor(Math.random() * tunes.length)])
document.write (audiopath)

This part works too, when the URL is defined as a constant.

var song = new audio('http://example.net/abcd.ogg');
song.play();

When I try to replace the constant URL with the variable audiopath, it fails to play.
May it be anything wrong with the syntax? I tried to run it with and without single quotes in the URL '"http://example.net/ijkl.ogg"' or "http://example.net/ijkl.ogg"

var song = new audio(audiopath);
song.play();




Aucun commentaire:

Enregistrer un commentaire