How to change play/button images in html5 audio

2019-08-17 17:42发布

问题:

I have the code of audio player. Please halp me to change the picture of play/pause button when press. Unfortunately i`m not strong in js (

<div class="onlineradio"><img src="images/Radio.jpg" alt="" />
<p><video id="yourAudio" width="0" height="0">
    <source src='http://178.219.160.126:8000/stream.mp3' type='audio/mpeg' preload="auto" />
</video> <a id="audioControl" href="#"><img src="images/radioscalebutton.png" alt="" /></a></p>
</div>
<script>// <![CDATA[
var yourAudio = document.getElementById('yourAudio'),
    ctrl = document.getElementById('audioControl');

ctrl.onclick = function () {

    // Update the Button
    var pause = ctrl.innerHTML === 'pause!';
    ctrl.innerHTML = pause ? 'pause' : 'play';

    // Update the Audio
    var method = pause ? 'pause' : 'play';
    yourAudio[method]();

    // Prevent Default Action
    return false;
};
// ]]></script>

回答1:

I have implemented a final working solution with custom audio controls (play and pause) with toggling state button. If something is not clear for you, please ask.

Here is the working solution and the JSFiddle:

var yourAudio = document.getElementById('yourAudio'),
    ctrl = document.getElementById('audioControl'),
    playButton = document.getElementById('play'),
    pauseButton = document.getElementById('pause');

function toggleButton() {
    if (playButton.style.display === 'none') {
        playButton.style.display = 'block';
        pauseButton.style.display = 'none';
    } else {
        playButton.style.display = 'none';
        pauseButton.style.display = 'block';
    }
}

ctrl.onclick = function () {

    if (yourAudio.paused) {
        yourAudio.play();
    } else {
        yourAudio.pause();
    }
    
    toggleButton();

    // Prevent Default Action
    return false;
};
#audioControl img {
    width: 50px;
    height: 50px;
}

#pause {
    display: none;
}
<div class="onlineradio">
    <img src="images/Radio.jpg" alt="" />
    <p>
        <audio id="yourAudio">
            <source src='http://178.219.160.126:8000/stream.mp3' type='audio/mpeg' preload="auto" />
        </audio>
        <a id="audioControl" href="#">
            <img src="http://etc-mysitemyway.s3.amazonaws.com/icons/legacy-previews/icons/glossy-black-3d-buttons-icons-media/002110-glossy-black-3d-button-icon-media-a-media22-arrow-forward1.png" id="play"/>
            <img src="https://www.wisc-online.com/asset-repository/getfile?id=415&getType=view" id="pause"/>
        </a>
    </p>
</div>

You can download the images of controls and use refer to them locally.



回答2:

The solution proposed by Karlen Kishmiryan will only work if there is one audio button per page.