xd1936
xd1936

Reputation: 1180

Trouble with Playing Audio when Image is Clicked

I've got the following code in my html document:

    <script>
    function playSound() {
      document.getElementById("easteregg").innerHTML= "<embed src=\"file.mp3\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
    }
    </script>

    <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand"><img src="img/logo.png" width="180px" onclick="playSound();" /></a>
    </div>

    <span id="easteregg"></span>

Nothing happens when I click the logo. Thoughts?

Edit: Found a solution.

I took Blake McConnell's advice and converted to the <audio> tag.

Code:

    audio { 
        display:none;
    }

    <a class="navbar-brand"><img src="img/logo.png" width="180px" onclick="document.getElementById('easteregg').play();" /></a>

    <audio id="easteregg" src="file.mp3" type="audio/mpeg" hidden="true" controls="false"></audio>

Upvotes: 3

Views: 52

Answers (1)

Blake McConnell
Blake McConnell

Reputation: 133

Try substituting "autoplay" for the "autostart" attribute in the embed tag.

I may be misunderstanding what you are trying to do, but wouldn't it be easier to attach an event listener to your span and use that to play back audio using the Web Audio API?

Upvotes: 1

Related Questions