Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   HTML5 audio вопросы (https://javascript.ru/forum/misc/48253-html5-audio-voprosy.html)

jule 26.06.2014 21:56

HTML5 audio вопросы
 
Доброго времени суток!Во время изучения HML5 audio, возникли вопросы.
Есть код:
<!DOCTYPE>
<html>
<head>
<title>HTML5 audio player</title>

</head>
<style type="text/css">
#player{
position:absolute;
border-radius:6px;
background-color:#000;
opacity:0.8;
height:30px;
padding:10px;
}
#switcher{
position:relative;
display:inline-block;
}
#progress{
position:relative;
display:inline-block;
border:1px solid #fff;
height:10px;
top:0px;
width:100px;
}
#loading{
position:relative;
background-color:#fff;
height:10px;
width:0px;
}
#buffered{
position:relative;
background-color:#fff;
height:10px;
opacity:0.5;
top:-10px;
}

</style>
<body>
<div id="player">
<button id="switcher">Play</button>
<div id="progress">
<div id="loading"></div>
<div id="buffered"></div>
</div>

</div>
<audio id="audio">
<source src="audio.mp3" type="audio/mp3"/>
</audio>

<script type="text/javascript">

var audio = document.getElementById("audio"),
    switcher = document.getElementById("switcher"),
    progress = document.getElementById("progress"),
    duration = document.getElementById("duration"),
    loading = document.getElementById("loading"),
    buffered = document.getElementById("buffered");
    
switcher.addEventListener("click", function(){
	if(switcher.innerHTML == "Play"){
		audio.play();
		switcher.innerHTML = "Pause";
	}	
	else{
		audio.pause();
		switcher.innerHTML = "Play";
	}
},false);
	
switcher.addEventListener("ended",function(){
	audio.pause();
	switcher.innerHTML = "Play";
},false);
switcher.addEventListener("play",function(){
	switcher.innerHTML = "Pause";
},false);
switcher.addEventListener("pause",function(){
	switcher.innerHTML = "Play";
},false);

progress.style.width = 100;
audio.addEventListener("timeupdate",function(){					
	loading.style.width = (audio.currentTime / audio.duration)*parseInt(progress.style.width); 
},false);
audio.addEventListener("progress",function(){						
	buffered.style.width = (audio.seekable.end(0) / audio.duration)*parseInt(progress.style.width); 

},false);

progress.addEventListener("click",function(event){
	audio.currentTime = Math.round(((event.pageX - this.offsetLeft)/parseInt(this.style.width))*audio.duration);
},false);

</script>
</body>
</html>


Вопросы:

1.При клике на определённую область элемента с id="progress":
progress.addEventListener("click",function(event){
	audio.currentTime = Math.round(((event.pageX - this.offsetLeft)/parseInt(this.style.width))*audio.duration);
},false);


Должно меняться текущее время мелодии, а следовательно, должна меняться длина элемента loading:
audio.addEventListener("timeupdate",function(){					
	loading.style.width = (audio.currentTime / audio.duration)*parseInt(progress.style.width); 
},false);

Но вся проблема в том, что она сдвигается немного дальше курсора (когда потестите - увидите), и не получается попасть в некоторые моменты мелодии сразу.

2.Второй вопрос, на мой взгляд, ещё интереснее - в браузере Chrome при проигрывании вот этой мелодии:
http://myzuka.ru/Song/3140254/Cold-War-Kids-Tuxedos

Если изменить текущее время песни, то когда ползунок дойдёт до конца прогрессбара, песня ещё будет проигрываться.Если текущее время не менять, то всё будет как надо.

Заранее спасибо.

jule 27.06.2014 17:15

По поводу 2 вопроса: потестив мелодию на фреймворке MediaElementsJs, мною было замечено, что проблема не в коде, а что это какой-то баг в браузере.

Zzz_jameson_zzZ 28.06.2014 16:05

Цитата:

Но вся проблема в том, что она сдвигается немного дальше курсора (когда потестите - увидите), и не получается попасть в некоторые моменты мелодии сразу.
Код тестить лень, но судя по стилям, думаю, в скрипте не все offsetLeft-ы учтены.
Попробуйте так:
var player = document.getElementById("player");
progress.addEventListener("click",function(event){
    audio.currentTime = Math.round((((event.pageX - this.offsetLeft - player.offsetLeft)/parseInt(this.style.width))*audio.duration));
},false);

По идее должно работать. Если что - пишите.
P.S. Советую лучше использовать готовые решения воспроизведения аудио на сайтах. Так будет практичнее, чем писать с нуля.


Часовой пояс GMT +3, время: 00:03.