当前位置:网站首页>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
边栏推荐
- Report on the development trend and prospect trend of high purity zinc antimonide market in the world and China Ⓕ 2022 ~ 2027
- Four common methods of copying object attributes (summarize the highest efficiency)
- HMS core helps baby bus show high-quality children's digital content to global developers
- 2022-2028 global edible probiotic raw material industry research and trend analysis report
- Upgrading Xcode 12 caused Carthage to build cartfile containing only rxswift to fail
- 2022-2028 global intelligent interactive tablet industry research and trend analysis report
- Function comparison between cs5261 and ag9310 demoboard test board | cost advantage of cs5261 replacing ange ag9310
- 什么是权限?什么是角色?什么是用户?
- Solution to null JSON after serialization in golang
- Lauchpad x | MODE
猜你喜欢
【LeetCode 42】501. Mode in binary search tree
How do microservices aggregate API documents? This wave of show~
Four common methods of copying object attributes (summarize the highest efficiency)
2022-2028 global visual quality analyzer industry research and trend analysis report
Reload CUDA and cudnn (for tensorflow and pytorch) [personal sorting summary]
HMS core helps baby bus show high-quality children's digital content to global developers
2022-2028 global elastic strain sensor industry research and trend analysis report
C语言-入门-基础-语法-[运算符,类型转换](六)
ArrayBuffer
PHP book borrowing management system, with complete functions, supports user foreground management and background management, and supports the latest version of PHP 7 x. Database mysql
随机推荐
C language - Introduction - Foundation - syntax - [main function, header file] (II)
DR6018-CP01-wifi6-Qualcomm-IPQ6010-IPQ6018-FAMILY-2T2R-2.5G-ETH-port-CP01-802-11AX-MU-MIMO-OFDMA
《网络是怎么样连接的》读书笔记 - FTTH
Nurse level JDEC addition, deletion, modification and inspection exercise
Flutter tips: various fancy nesting of listview and pageview
Tkinter Huarong Road 4x4 tutorial II
Research Report on the development trend and Prospect of global and Chinese zinc antimonide market Ⓚ 2022 ~ 2027
[on February 11, 2022, the latest and most fully available script library collection of the whole network, a total of 23]
What is uid? What is auth? What is a verifier?
Target detection -- intensive reading of yolov3 paper
Implementation principle of redis string and sorted set
Write a jison parser from scratch (2/10): learn the correct posture of the parser generator parser generator
About the for range traversal operation in channel in golang
Write a jison parser (7/10) from scratch: the iterative development process of the parser generator 'parser generator'
Simulate EF dbcontext with MOQ - mocking EF dbcontext with MOQ
Ultimate bug finding method - two points
Rules for using init in golang
Trees and graphs (traversal)
GoLand environment variable configuration
C language - Introduction - Foundation - syntax - [variable, constant light, scope] (V)