How to trigger background audio by clicking a button?

Discussion in 'HTML & Website Design' started by BobJason, Jun 23, 2015.

  1. #1
    I want the background music to start only when my self-generated button is clicked.
    Here is my code:

    <a href="audio/listen.mp3" autostart="false"loop="false"width="2"height="0" class="learn-more-btn">Listen.</a>

    The problem is, it opens the audio on a separate page instead of invisibly in the background.
    Thank you.
     
    Solved! View solution.
    BobJason, Jun 23, 2015 IP
  2. 2WDH.com

    2WDH.com Active Member

    Messages:
    143
    Likes Received:
    3
    Best Answers:
    5
    Trophy Points:
    68
    #2
    Hi.

    This should help:
    
    
    <audio src="/path/to/musicFile" id="bgAudio"></audio>
    <button onclick="document.getElementById('bgAudio').play();">Play</button>
    <button onclick="document.getElementById('bgAudio').pause();">Pause</button>
    HTML:
     
    2WDH.com, Jun 23, 2015 IP
  3. BobJason

    BobJason Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #3
    Thanks 2WDH.com for your help.
    buttons.PNG
    Now I have three buttons. I only want the "LISTEN"-Button to appear for both purposes. And the music shall sound even when the main page is left while any subpage is visited. For the audio I would also accept the music of an YouTube video.
    Thank you so much.
     
    BobJason, Jun 23, 2015 IP
  4. #4
    One button:
    
    
    <script>
    var bgAudio = new Audio();
    bgAudio.setAttribute("src","/path/to/musicFile");
    bgAudio.loop = true;
    </script>
    <button onclick="if ( bgAudio.paused ) { bgAudio.play(); } else { bgAudio.pause(); }">Play / Pause</button>
    HTML:
    Regarding the sound even when the main page is left - you can try to use frames or ajax to load content for example.
     
    2WDH.com, Jun 23, 2015 IP
  5. BobJason

    BobJason Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #5
    Thank you so much.
    This is the result:
    2buttons.PNG
    The left one is the original button without the desired function and the right one is the button we are working on. Now I want to get rid of the default border on the left. How would you do what?
     
    BobJason, Jun 24, 2015 IP
  6. 2WDH.com

    2WDH.com Active Member

    Messages:
    143
    Likes Received:
    3
    Best Answers:
    5
    Trophy Points:
    68
    #6
    If you are using button element then you can change it back to what you have used before (without the default border) with the onclick attribute.
     
    2WDH.com, Jun 24, 2015 IP
  7. BobJason

    BobJason Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #7
    Sorry I asked the wrong question. The problem is solved. There was some issue with the classes.

    Thank you.
     
    BobJason, Jun 24, 2015 IP