[英]Audio looping in JavaScript
I have an audio file that is 10 seconds long and I want to play it when user clicks on button. 我有一个10秒长的音频文件,我想在用户单击按钮时播放它。 However when user holds the button down I want my audio to play on a loop from 5s to 7.5s and
onmouseup
I need my audio to play through the end(10s). 但是,当用户按下按钮时,我希望我的音频从5s到7.5s循环播放,而
onmouseup
需要我的音频播放到10s。 Is it possible to do this without any external libraries? 没有任何外部库,是否可以这样做?
So I created the following JS Fiddle that does the looping over 5-7.5 onmousedown
. 因此,我创建了以下JS小提琴 ,它在5-7.5
onmousedown
上进行循环。 It works by keeping track of the currentTime
property and checking to see if the player is in or out of bounds, resetting if outside bounds. 它通过跟踪
currentTime
属性并检查播放器是否在范围内,并在超出范围时重置来工作。
<button onclick="playSound()">play</button>
<button onmousedown="fivetoseven()">play 5-7</button>
<button onclick="stopSound()">stop</button>
<audio controls id="mp3" preload="auto" src="https://upload.wikimedia.org/wikipedia/commons/4/40/Toreador_song_cleaned.ogg"></audio>
<script>
var mp3 = document.getElementById('mp3');
function playSound() {
mp3.play();
}
function fivetoseven() {
if (mp3.currentTime < 5.0 || mp3.currentTime > 7.5) {
mp3.currentTime = 5;
}
setTimeout(fivetoseven, 500)
}
function stopSound() {
mp3.pause();
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.