Cómo construir un reproductor de audio con HTML5 y el elemento Progreso
HTML5 introduce el soporte multimedia integrado con la
audio
etiqueta, lo que hace que sea muy fácil incrustar los medios directamente en cualquier documento HTML con código limitado. Viene con controles de navegador incorporados, si especifica y reproduce el audio de forma agradable y eficaz.
Esto suele ser el aspecto que tendrá en su navegador (algunos pueden variar).
Podría estar pensando: "Bueno, ¿y si quisiera estilizar mi propio reproductor de audio con sus propios botones y barra de desplazamiento?"
¡Con el
audio
elemento, el progress
elemento y unos pocos botones, puede crear su propio reproductor de audio en muy poco tiempo! El elemento de progreso se utiliza principalmente para rastrear la finalización de una tarea y se puede manipular fácilmente con Javascript. En nuestro caso, sería hacer un seguimiento de la duración de una canción. Y lo mejor es que HTML5 y las capacidades del navegador facilitan la obtención de la duración de las canciones, la hora actual y más.debajo está el código. Tenga en cuenta que hay dos funciones separadas. Uno que realiza un seguimiento del reproductor de audio que realmente reproduce audio (función initPlayers) y el otro que realiza un seguimiento del audio para el elemento de progreso (función initProgressBar). Traté de mantener jQuery al mínimo, pero lo usé para llamar a la función, lo siento, no lo siento, puristas de JS.
Codigo Html
<div class="audio-player">
<div id="play-btn"></div>
<div class="audio-wrapper" id="player-container" href="javascript:;">
<audio id="player" ontimeupdate="initProgressBar()">
<source src="https://dl-web.dropbox.com/get/Oslo.mp3?_subject_uid=199049471&w=AABuDNt9BDJnaZOelVFws9FXTufkXCvAPS5SYpy_gRZ2GQ&duc_id=dropbox_duc_id" type="audio/mp3">
</audio>
</div>
<div class="player-controls scrubber">
<p>Oslo <small>by</small> Holy Esque</p>
<span id="seek-obj-container">
<progress id="seek-obj" value="0" max="1"></progress>
</span>
<small style="float: left; position: relative; left: 15px;" id="start-time"></small>
<small style="float: right; position: relative; right: 20px;" id="end-time"></small>
</div>
<div class="album-image" style="background-image: url(https://artistxite.ie/imgcache/album/005/161/005161476_500.jpg)"></div>
</div>
Guardar como audio-player.html
Siguiente Codigo
function initProgressBar() {
var player = document.getElementById('player');
var length = player.duration
var current_time = player.currentTime;
// calculate total length of value
var totalLength = calculateTotalValue(length)
document.getElementById("end-time").innerHTML = totalLength;
// calculate current value time
var currentTime = calculateCurrentValue(current_time);
document.getElementById("start-time").innerHTML = currentTime;
var progressbar = document.getElementById('seek-obj');
progressbar.value = (player.currentTime / player.duration);
progressbar.addEventListener("click", seek);
if (player.currentTime == player.duration) {
document.getElementById('play-btn').className = "";
}
function seek(event) {
var percent = event.offsetX / this.offsetWidth;
player.currentTime = percent * player.duration;
progressbar.value = percent / 100;
}
};
function initPlayers(num) {
// pass num in if there are multiple audio players e.g 'player' + i
for (var i = 0; i < num; i++) {
(function() {
// Variables
// ----------------------------------------------------------
// audio embed object
var playerContainer = document.getElementById('player-container'),
player = document.getElementById('player'),
isPlaying = false,
playBtn = document.getElementById('play-btn');
// Controls Listeners
// ----------------------------------------------------------
if (playBtn != null) {
playBtn.addEventListener('click', function() {
togglePlay()
});
}
// Controls & Sounds Methods
// ----------------------------------------------------------
function togglePlay() {
if (player.paused === false) {
player.pause();
isPlaying = false;
document.getElementById('play-btn').className = "";
} else {
player.play();
document.getElementById('play-btn').className = "pause";
isPlaying = true;
}
}
}());
}
}
function calculateTotalValue(length) {
var minutes = Math.floor(length / 60),
seconds_int = length - minutes * 60,
seconds_str = seconds_int.toString(),
seconds = seconds_str.substr(0, 2),
time = minutes + ':' + seconds
return time;
}
function calculateCurrentValue(currentTime) {
var current_hour = parseInt(currentTime / 3600) % 24,
current_minute = parseInt(currentTime / 60) % 60,
current_seconds_long = currentTime % 60,
current_seconds = current_seconds_long.toFixed(),
current_time = (current_minute < 10 ? "0" + current_minute : current_minute) + ":" + (current_seconds < 10 ? "0" + current_seconds : current_seconds);
return current_time;
}
initPlayers(jQuery('#player-container').length);
Guardar como audio-player.js
Siguiente Codigo el css
.audio-player {
border: 1px solid lighten(#acacac, 20%);
text-align: center;
display: flex;
flex-flow: row;
margin: 4rem 0 4rem 0;
width: 600px;
.album-image {
min-height: 100px;
width: 100px;
background-size: cover;
}
.player-controls {
align-items: center;
justify-content: center;
margin-top: 2.5rem;
flex: 3;
progress {
width: 90%;
}
progress[value] {
-webkit-appearance: none;
appearance: none;
background-color: white;
color: blue;
height: 5px;
}
progress[value]::-webkit-progress-bar {
background-color: white;
border-radius: 2px;
border: 1px solid lighten(#acacac, 20%);
color: blue;
}
progress::-webkit-progress-value {
background-color: blue;
}
p {
font-size: 1.6rem;
}
}
#play-btn {
background-image: url('http://imgur.com/JzQP8td.png');
background-size: cover;
width: 75px;
height: 75px;
margin: 2rem 0 2rem 2rem;
&.pause {
background-image: url('http://imgur.com/MbJn41l.png');
}
}
}
Guardar como main.css
1 Comentarios
For mobile betting, internet site} offers full performance and security on its immediate play model. You can utilize all the site's features and play mobile casino games with touchscreen controls. Nearly all mobile gambling apps launched by prime names in the gaming business are absolutely secured. These apps come with state-of-the-art security features 온라인카지노 and end-to-end encryption. There is little probability of any hacker accessing users’ private particulars and causing any type of financial or knowledge danger. Yes, and some provide particular bonus deals for smartphone players too.
ResponderEliminar