当前位置:网站首页>H5 audio tag custom style modification and adding playback control events

H5 audio tag custom style modification and adding playback control events

2022-07-04 09:34:00 Dandelion_ drq

20181023 to update
The original code drag progress point is only written mouse event , On the mobile end, it should be touch event . Therefore, a friend said that the mobile end cannot drag the progress bar . Now the updated code has been added touch event , That is, whether browsing in mobile mode , still PC Mode browsing can drag the progress point to adjust the audio playback progress . The complete code has also been put on the code cloud , Students who need it can download it by themselves .


explain :

It is required that this audio tag should be compatible with mobile browser first , The audio style is made with reference to wechat .

The end result is as follows :


Concrete realization

Ideas :

H5 Of <audio> The browser is responsible for the default style of tags . So different browsers have different styles , Some are not very beautiful . So we usually get rid of the default style , Rewrite it yourself . The specific operation is to define <audio> Get rid of controls attribute , In this way, you can hide the original audio, Then you can add your own html + css Code. . Last use js Capture audio object , Add various playback control events to it .


1. Define Tags

This is very simple , Just use H5 <audio> How tags define audio .

html Code :

<div class="audio-wrapper">
    <audio>
        <source src="Files/Audio/2017-08/e259d760-5f1a-4ae0-a838-34d237ea93cc.mp3" type="audio/mp3">
    </audio>
    <div class="audio-left">![](image/play.png)</div>
    <div class="audio-right">
        <p style="max-width: 536px;">Beta-B_Kan R. Gao.mp3</p>
        <div class="progress-bar-bg" id="progressBarBg"><span id="progressDot"></span>
            <div class="progress-bar" id="progressBar"></div>
        </div>
        <div class="audio-time"><span class="audio-length-current" id="audioCurTime">00:00</span><span class="audio-length-total">01:06</span></div>
    </div>
</div>

css Code :

.audio-wrapper {
    
    background-color: #fcfcfc;
    margin: 10px auto;
    max-width: 670px;
    height: 70px;
    border: 1px solid #e0e0e0;
}

.audio-left {
    
    float: left;
    text-align: center;
    width: 18%;
    height: 100%;
}

.audio-left img {
    
    width: 40px;
    position: relative;
    top: 15px;
    margin: 0;
    display: initial;   /*  Release and app The pattern conflict of  */
    cursor: pointer;
}

.audio-right {
    
    margin-right: 2%;
    float: right;
    width: 80%;
    height: 100%;
}

.audio-right p {
    
    font-size: 15px;
    height: 35%;
    margin: 8px 0;

    /*  The song name is only displayed on one line , The excess is shown as an ellipsis  */
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    max-width: 243px;   /*  To adapt to small screen mobile phones , So let the maximum width be smaller , Back js Reset according to the screen size  */    
}

.progress-bar-bg {
    
    background-color: #d9d9d9;
    position: relative;
    height: 2px;
    cursor: pointer;
}

.progress-bar {
    
    background-color: #649fec;
    width: 0;
    height: 2px;
}

.progress-bar-bg span {
    
    content: " ";
    width: 10px;
    height: 10px;
    border-radius: 50%;
    -moz-border-radius: 50%;
    -webkit-border-radius: 50%;
    background-color: #3e87e8;
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -5px;
    margin-left: -5px;
    cursor: pointer;
}

.audio-time {
    
    overflow: hidden;
    margin-top: -1px;
}

.audio-length-total {
    
    float: right;
    font-size: 12px;
}

.audio-length-current {
    
    float: left;
    font-size: 12px;
}

2. Add playback control event

  • Get audio object
var audio = document.getElementsByTagName('audio')[0];
  • Play / Pause control
    //  Click play / When pausing pictures , Control the playback and pause of music 
    var audioPlayer = document.getElementById('audioPlayer');
    audioPlayer.addEventListener('click', function () {
    
        //  Change playback / Pause the picture 
        if (audio.paused) {
    
            audio.play();
            audioPlayer.src = './image/pause.png';
        } else {
    
            audio.pause();
            audioPlayer.src = './image/play.png';
        }
    }, false);
  • Update the progress bar and the current playback time
//  Monitor the audio playback time and update the progress bar 
audio.addEventListener('timeupdate', function () {
    
    updateProgress(audio);
}, false);

/** *  Update the progress bar and the current playback time  * @param {object} audio - audio object  */
function updateProgress(audio) {
    
    var value = audio.currentTime / audio.duration;
    document.getElementById('progressBar').style.width = value * 100 + '%';
    document.getElementById('progressDot').style.left = value * 100 + '%';
    document.getElementById('audioCurTime').innerText = transTime(audio.currentTime);
}

/** *  Audio playback time conversion  * @param {number} value -  Current audio playback time , Unit second  */
function transTime(value) {
    
    var time = "";
    var h = parseInt(value / 3600);
    value %= 3600;
    var m = parseInt(value / 60);
    var s = parseInt(value % 60);
    if (h > 0) {
    
        time = formatTime(h + ":" + m + ":" + s);
    } else {
    
        time = formatTime(m + ":" + s);
    }

    return time;
}

/** *  Format time display , Zero padding  * eg:2:4 --> 02:04 * @param {string} value -  Form like  h:m:s  String  */
function formatTime(value) {
    
    var time = "";
    var s = value.split(':');
    var i = 0;
    for (; i < s.length - 1; i++) {
    
        time += s[i].length == 1 ? ("0" + s[i]) : s[i];
        time += ":";
    }
    time += s[i].length == 1 ? ("0" + s[i]) : s[i];

    return time;
}
  • When the playback is finished, adjust the progress back to the starting position
//  Listen for the playback completion event 
audio.addEventListener('ended', function () {
    
    audioEnded();
}, false);

/** *  When the playback is finished, adjust the progress back to the starting position  */
function audioEnded() {
    
    document.getElementById('progressBar').style.width = 0;
    document.getElementById('progressDot').style.left = 0;
    document.getElementById('audioCurTime').innerText = transTime(0);
    document.getElementById('audioPlayer').src = './image/play.png';
}

3. Add progress adjustment event

  • Click the progress bar to jump to the specified position to play
    //  Click the progress bar to jump to the specified point to play 
    // PS: Don't use it here click, Otherwise, the following drag progress point event may be triggered here , here e.offsetX The value of is very small , It will cause the progress bar to bounce back to the beginning ( I can't bear it !!)
    var progressBarBg = document.getElementById('progressBarBg');
    progressBarBg.addEventListener('mousedown', function (event) {
    
        //  You can only adjust the music after it starts playing , You can also play something that has been played but has been paused 
        if (!audio.paused || audio.currentTime != 0) {
    
            var pgsWidth = parseFloat(window.getComputedStyle(progressBarBg, null).width.replace('px', ''));
            var rate = event.offsetX / pgsWidth;
            audio.currentTime = audio.duration * rate;
            updateProgress(audio);
        }
    }, false);
  • Drag the progress bar to the specified position to play
/** *  When dragging the progress point with the mouse, you can adjust the progress  * @param {*} audio */
function dragProgressDotEvent(audio) {
    
    var dot = document.getElementById('progressDot');

    var position = {
    
        oriOffestLeft: 0, //  The offset value between the point of the progress bar and the progress bar at the beginning of the movement 
        oriX: 0, //  At the beginning of the move x coordinate 
        maxLeft: 0, //  The maximum drag distance to the left 
        maxRight: 0 //  The maximum drag distance to the right 
    };
    var flag = false; //  Mark whether to drag to start 

    //  When the mouse is pressed 
    dot.addEventListener('mousedown', down, false);
    dot.addEventListener('touchstart', down, false);

    //  Start drag 
    document.addEventListener('mousemove', move, false);
    document.addEventListener('touchmove', move, false);

    //  Drag end 
    document.addEventListener('mouseup', end, false);
    document.addEventListener('touchend', end, false);

    function down(event) {
    
        if (!audio.paused || audio.currentTime != 0) {
     //  You can only adjust the music after it starts playing , You can also play something that has been played but has been paused 
            flag = true;

            position.oriOffestLeft = dot.offsetLeft;
            position.oriX = event.touches ? event.touches[0].clientX : event.clientX; //  It should be adapted at the same time mousedown and touchstart event 
            position.maxLeft = position.oriOffestLeft; //  The maximum drag distance to the left 
            position.maxRight = document.getElementById('progressBarBg').offsetWidth - position.oriOffestLeft; //  The maximum drag distance to the right 

            //  Disable default events ( Avoid selecting text when dragging progress points with the mouse )
            if (event && event.preventDefault) {
    
                event.preventDefault();
            } else {
    
                event.returnValue = false;
            }

            //  No bubbling of events 
            if (event && event.stopPropagation) {
    
                event.stopPropagation();
            } else {
    
                window.event.cancelBubble = true;
            }
        }
    }

    function move(event) {
    
        if (flag) {
    
            var clientX = event.touches ? event.touches[0].clientX : event.clientX; //  It should be adapted at the same time mousemove and touchmove event 
            var length = clientX - position.oriX;
            if (length > position.maxRight) {
    
                length = position.maxRight;
            } else if (length < -position.maxLeft) {
    
                length = -position.maxLeft;
            }
            var progressBarBg = document.getElementById('progressBarBg');
            var pgsWidth = parseFloat(window.getComputedStyle(progressBarBg, null).width.replace('px', ''));
            var rate = (position.oriOffestLeft + length) / pgsWidth;
            audio.currentTime = audio.duration * rate;
            updateProgress(audio);
        }
    }

    function end() {
    
        flag = false;
    }
}

Finally, in general js The code is as follows :

document.addEventListener('DOMContentLoaded', function () {
    
    //  Set the display width of audio file name 
    var element = document.querySelector('.audio-right');
    var maxWidth = window.getComputedStyle(element, null).width;
    document.querySelector('.audio-right p').style.maxWidth = maxWidth;

    //  Initialize the audio control event 
    initAudioEvent();
}, false);

function initAudioEvent() {
    
    var audio = document.getElementsByTagName('audio')[0];
    var audioPlayer = document.getElementById('audioPlayer');

    //  Click play / When pausing pictures , Control the playback and pause of music 
    audioPlayer.addEventListener('click', function () {
    
        //  Monitor the audio playback time and update the progress bar 
        audio.addEventListener('timeupdate', function () {
    
            updateProgress(audio);
        }, false);

        //  Listen for the playback completion event 
        audio.addEventListener('ended', function () {
    
            audioEnded();
        }, false);

        //  Change playback / Pause the picture 
        if (audio.paused) {
    
            //  Start playing the currently clicked audio 
            audio.play();
            audioPlayer.src = './image/pause.png';
        } else {
    
            audio.pause();
            audioPlayer.src = './image/play.png';
        }
    }, false);

    //  Click the progress bar to jump to the specified point to play 
    // PS: Don't use it here click, Otherwise, the following drag progress point event may be triggered here , here e.offsetX The value of is very small , It will cause the progress bar to bounce back to the beginning ( I can't bear it !!)
    var progressBarBg = document.getElementById('progressBarBg');
    progressBarBg.addEventListener('mousedown', function (event) {
    
        //  You can only adjust the music after it starts playing , You can also play something that has been played but has been paused 
        if (!audio.paused || audio.currentTime != 0) {
    
            var pgsWidth = parseFloat(window.getComputedStyle(progressBarBg, null).width.replace('px', ''));
            var rate = event.offsetX / pgsWidth;
            audio.currentTime = audio.duration * rate;
            updateProgress(audio);
        }
    }, false);

    //  Drag the progress point to adjust the progress 
    dragProgressDotEvent(audio);
}

/** *  When dragging the progress point with the mouse, you can adjust the progress  * @param {*} audio */
function dragProgressDotEvent(audio) {
    
    var dot = document.getElementById('progressDot');

    var position = {
    
        oriOffestLeft: 0, //  The offset value between the point of the progress bar and the progress bar at the beginning of the movement 
        oriX: 0, //  At the beginning of the move x coordinate 
        maxLeft: 0, //  The maximum drag distance to the left 
        maxRight: 0 //  The maximum drag distance to the right 
    };
    var flag = false; //  Mark whether to drag to start 

    //  When the mouse is pressed 
    dot.addEventListener('mousedown', down, false);
    dot.addEventListener('touchstart', down, false);

    //  Start drag 
    document.addEventListener('mousemove', move, false);
    document.addEventListener('touchmove', move, false);

    //  Drag end 
    document.addEventListener('mouseup', end, false);
    document.addEventListener('touchend', end, false);

    function down(event) {
    
        if (!audio.paused || audio.currentTime != 0) {
     //  You can only adjust the music after it starts playing , You can also play something that has been played but has been paused 
            flag = true;

            position.oriOffestLeft = dot.offsetLeft;
            position.oriX = event.touches ? event.touches[0].clientX : event.clientX; //  It should be adapted at the same time mousedown and touchstart event 
            position.maxLeft = position.oriOffestLeft; //  The maximum drag distance to the left 
            position.maxRight = document.getElementById('progressBarBg').offsetWidth - position.oriOffestLeft; //  The maximum drag distance to the right 

            //  Disable default events ( Avoid selecting text when dragging progress points with the mouse )
            if (event && event.preventDefault) {
    
                event.preventDefault();
            } else {
    
                event.returnValue = false;
            }

            //  No bubbling of events 
            if (event && event.stopPropagation) {
    
                event.stopPropagation();
            } else {
    
                window.event.cancelBubble = true;
            }
        }
    }

    function move(event) {
    
        if (flag) {
    
            var clientX = event.touches ? event.touches[0].clientX : event.clientX; //  It should be adapted at the same time mousemove and touchmove event 
            var length = clientX - position.oriX;
            if (length > position.maxRight) {
    
                length = position.maxRight;
            } else if (length < -position.maxLeft) {
    
                length = -position.maxLeft;
            }
            var progressBarBg = document.getElementById('progressBarBg');
            var pgsWidth = parseFloat(window.getComputedStyle(progressBarBg, null).width.replace('px', ''));
            var rate = (position.oriOffestLeft + length) / pgsWidth;
            audio.currentTime = audio.duration * rate;
            updateProgress(audio);
        }
    }

    function end() {
    
        flag = false;
    }
}

/** *  Update the progress bar and the current playback time  * @param {object} audio - audio object  */
function updateProgress(audio) {
    
    var value = audio.currentTime / audio.duration;
    document.getElementById('progressBar').style.width = value * 100 + '%';
    document.getElementById('progressDot').style.left = value * 100 + '%';
    document.getElementById('audioCurTime').innerText = transTime(audio.currentTime);
}

/** *  When the playback is finished, adjust the progress back to the starting position  */
function audioEnded() {
    
    document.getElementById('progressBar').style.width = 0;
    document.getElementById('progressDot').style.left = 0;
    document.getElementById('audioCurTime').innerText = transTime(0);
    document.getElementById('audioPlayer').src = './image/play.png';
}

/** *  Audio playback time conversion  * @param {number} value -  Current audio playback time , Unit second  */
function transTime(value) {
    
    var time = "";
    var h = parseInt(value / 3600);
    value %= 3600;
    var m = parseInt(value / 60);
    var s = parseInt(value % 60);
    if (h > 0) {
    
        time = formatTime(h + ":" + m + ":" + s);
    } else {
    
        time = formatTime(m + ":" + s);
    }

    return time;
}

/** *  Format time display , Zero padding  * eg:2:4 --> 02:04 * @param {string} value -  Form like  h:m:s  String  */
function formatTime(value) {
    
    var time = "";
    var s = value.split(':');
    var i = 0;
    for (; i < s.length - 1; i++) {
    
        time += s[i].length == 1 ? ("0" + s[i]) : s[i];
        time += ":";
    }
    time += s[i].length == 1 ? ("0" + s[i]) : s[i];

    return time;
}

Reference resources :

Audio (audio) Custom styles and control panel
HTML5 in audio Label style modification


Complete code

https://gitee.com/Dandelion_/html_demo/tree/master/H5-audio

原网站

版权声明
本文为[Dandelion_ drq]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141425121691.html