简体   繁体   中英

How to play sound with Javascript?

I am struggling to make the play icon active and play a sound. Can anyone help me?

Here is my HTML:

<div class="buttons">
    <a id="play" href="#" class="btn">
        <audio id="myaudio">
            <source src="media/tasmanian-devil-daniel_simon.mp3" preload="auto"  > 
        </audio>
        <br>
        <i class="fas fa-play"></i>
    </a>
</div>

I think you might need to add the controls attribute to your <audio> tag. That way you don't need the extra button(s).

It would look like this:

<div class="buttons">
    <audio id="myaudio" controls>
        <source src="media/tasmanian-devil-daniel_simon.mp3" preload="auto">
    </audio>
</div>

Method 1 - with default control
Answer by Niels Bosman

Method 2 - with custom button

-- JS  
const myaudioInput = document.querySelector('#myaudio');

function playAudio() {
 myaudioInput.play();
}

-- HTML  
<i class="fa fa-play" onclick="playAudio()"></i>

to pause

myaudioInput.pause();

to restart

myaudioInput.pause();
myaudioInput.currentTime = 0;
myaudioInput.play();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM