当前位置:网站首页>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"></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
边栏推荐
- Global and Chinese trisodium bicarbonate operation mode and future development forecast report Ⓢ 2022 ~ 2027
- Nurse level JDEC addition, deletion, modification and inspection exercise
- If you can quickly generate a dictionary from two lists
- PMP registration process and precautions
- Analysis report on the production and marketing demand and investment forecast of tellurium dioxide in the world and China Ⓣ 2022 ~ 2027
- QTreeView+自定义Model实现示例
- Global and Chinese market of bipolar generators 2022-2028: Research Report on technology, participants, trends, market size and share
- Launchpad x | mode
- Write a jison parser from scratch (5/10): a brief introduction to the working principle of jison parser syntax
- 【leetcode】29. Divide two numbers
猜你喜欢
The child container margin top acts on the parent container
At the age of 30, I changed to Hongmeng with a high salary because I did these three things
2022-2028 research and trend analysis report on the global edible essence industry
2022-2028 global seeder industry research and trend analysis report
Reload CUDA and cudnn (for tensorflow and pytorch) [personal sorting summary]
C語言-入門-基礎-語法-[運算符,類型轉換](六)
PHP personal album management system source code, realizes album classification and album grouping, as well as album image management. The database adopts Mysql to realize the login and registration f
Sword finger offer 30 contains the stack of Min function
[C Advanced] file operation (2)
Function comparison between cs5261 and ag9310 demoboard test board | cost advantage of cs5261 replacing ange ag9310
随机推荐
How to ensure the uniqueness of ID in distributed environment
lolcat
Global and Chinese market of sampler 2022-2028: Research Report on technology, participants, trends, market size and share
Are there any principal guaranteed financial products in 2022?
Write a jison parser (7/10) from scratch: the iterative development process of the parser generator 'parser generator'
LeetCode 74. Search 2D matrix
《网络是怎么样连接的》读书笔记 - 集线器、路由器和路由器(三)
2022-2028 global optical transparency industry research and trend analysis report
Implementation principle of redis string and sorted set
Report on investment analysis and prospect trend prediction of China's MOCVD industry Ⓤ 2022 ~ 2028
2022-2028 global seeder industry research and trend analysis report
Target detection -- intensive reading of yolov3 paper
Dede plug-in (multi-function integration)
In depth investigation and Strategic Research Report on China's motion controller Market (2022 Edition)
How does idea withdraw code from remote push
Investment analysis and prospect prediction report of global and Chinese high purity tin oxide Market Ⓞ 2022 ~ 2027
PHP student achievement management system, the database uses mysql, including source code and database SQL files, with the login management function of students and teachers
《网络是怎么样连接的》读书笔记 - Tcp/IP连接(二)
What is inner connection and outer connection? What are the uses and benefits
C语言-入门-基础-语法-数据类型(四)