Help Me
Help Me

Reputation: 55

Adding background music to webpage

So, I've had some issues with this. Simply put, I want to have a play button on my webpage which plays TWO files simultaniously. The files are Jazz.ogg with Jazz.mp3 and Rain.ogg with Rain.mp3. The play button in the HTML is put such as;

<div class="play">
  <img src="play.png" style="height: 100%; width: 100%;">
</div>

I have a bit of experience with HTML and CSS, but when it comes to Javascript, I'm as much of use as the font-stretch element.

Upvotes: 2

Views: 1122

Answers (2)

pistou
pistou

Reputation: 2867

This is an html5 solution. Music will be played only once you clicked the play image.

<body>
    <script>
    function playMusic() {
        var jazzMusic = document.getElementById("audio-jazz");
        jazzMusic.play();

        var rainMusic = document.getElementById("audio-rain");
        rainMusic.play();
    }
    </script>

    <div class="play">
       <img src="play.png" style="height: 100%; width: 100%;" onclick="playMusic();">
    </div>
    <audio id="audio-jazz" src="Jazz.ogg"></audio>
    <audio id="audio-rain" src="Rain.ogg"></audio>
</body>

Make sure to add the right path to your .ogg files.

Upvotes: 1

Luciano Mammino
Luciano Mammino

Reputation: 811

Something like this should work for you:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin audio test</title>
</head>
<body>
  <div id="play">
   <img src="play.png" style="height: 100%; width: 100%;">
  </div>
  <audio id="audio-jazz">
    <source src="jazz.ogg" type="audio/ogg">
    <source src="jazz.mp3" type="audio/mpeg">
  </audio>
  <audio id="audio-rain">
    <source src="rain.ogg" type="audio/ogg">
    <source src="rain.mp3" type="audio/mpeg">
  </audio>
  <script>
    var playButton = document.getElementById('play');
    var rainAudio = document.getElementById('audio-rain');
    var jazzAudio = document.getElementById('audio-jazz');

    playButton.onclick = function(){
      rainAudio.play();
      jazzAudio.play();
      return false;
    };
  </script>
</body>
</html>

Here is a working (simplified) example: https://jsbin.com/yikifozedi/1/edit

Upvotes: 0

Related Questions