5

I want to create a site where I have a image, and if somebody click this image, a random song from a playlist or something like this should be played. I have a running code to activate one song, but if I want to have more than one song it doesn't work anymore.

<html>
  <head>
    <title>title</title>
        <link type="text/css" rel="stylesheet" href="style.css"/>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="script.js"></script>
  </head>
  <body>
    <div id="headline">
      <h1 id="hl">Headline</h1>
      <img class="play" id="pic" src="pic.png"/>
      <img class="pause" id="pic2" src="pic.png"/>
    </div>
  </body>
 </html>
$(document).ready(function() {

    $(".pause").css ('display', 'none');

    $(".play").click (function(){
        $(".play").css ('display', 'none');
        $(".pause").css ('display', 'inline-block');
    });
    $(".pause").click (function(){
        $(".play").css ('display', 'inline-block');
        $(".pause").css ('display', 'none');
    });

    var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', 'song1.mp3');
    /*var audioElement2 = document.createElement('audio');
    audioElement2.setAttribute('src', 'song2.mp3');*/

    $.get();

    audioElement.addEventListener("load", function() {
        audioElement.play();
    }, true);
    /*audioElement2.addEventListener("load", function() {
        audioElement2.play();
    }, true);*/

    var x = 1 /*Math.round(Math.random() * (2)) + 1*/;
    if (x = 1) {
        $('.play').click(function() {
        });
    /*} else {
        $('.play').click(function() {
            audioElement2.play();
        });*/
    }

    $('.pause').click(function() {
            audioElement.pause();
            audioElement2.pause();
    });
});

Now I want to have more than one song and I don't want to use a music player or so. Is there a way to solve this problem with HTML, JS, and jQuery?

TylerH
  • 20,799
  • 66
  • 75
  • 101
html user
  • 51
  • 1
  • 2
  • 2
    No need for multi language question. SO have userbase who're very well versed in English. This makes the question unnecessarily huge. – Java_User Oct 15 '15 at 13:03
  • 1
    Can you just change the src of the audio element to a random src? – Shilly Oct 15 '15 at 13:06

1 Answers1

1

You should have an array representing your playlist, then pick a random element from it and play it

Something like this:

var playlist = Array("song1.mp3", "song2.mp3", "song3.mp3");
var randomSong = playlist[Math.floor(Math.random()*playlist.length)];
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', randomSong);
/* ... your code continues here ... */
pistou
  • 2,799
  • 5
  • 33
  • 60