Javascript 将音频播放限制到指定范围
假设我有一个90秒长的音频文件 我希望加载此音频文件以供用户播放,但将播放限制在10秒到40秒之间 我正在努力实现的目标:Javascript 将音频播放限制到指定范围,javascript,html,html5-audio,Javascript,Html,Html5 Audio,假设我有一个90秒长的音频文件 我希望加载此音频文件以供用户播放,但将播放限制在10秒到40秒之间 我正在努力实现的目标: 音频从10秒开始 当音频结束时,它将重置为10秒标记 音频在40秒结束 无法访问范围之外的音频 var audiofile=document.getElementById(“myAudio”); var currenttime=audiofile.currenttime; 当前时间=10; 如果(currenttime>39){currenttime=10;} 例如:
- 音频从10秒开始
- 当音频结束时,它将重置为10秒标记
- 音频在40秒结束
- 无法访问范围之外的音频
var audiofile=document.getElementById(“myAudio”);
var currenttime=audiofile.currenttime;
当前时间=10;
如果(currenttime>39){currenttime=10;}
例如:
请注意,这不是一个好方法。用户必须下载整个文件,而不仅仅是截断的部分。您应该强烈考虑截断文件。您甚至可以使用音频编辑库在服务器端执行截断操作
还要注意,这并不准确。我已经在上面的示例中添加了当前时间的日志记录(在JavaScript控制台中查看)。你会注意到,你最多可以休息一秒钟。如果需要精度,可以缩短间隔时间
上述代码适用于最新版本的Firefox、Chrome和IE(我没有测试任何其他版本)。也有类似的问题
解决方案如下:如果有人试图选择“外部”,这会将播放拖到片段的开头,同样,在片段的结尾也会这样做:
<audio controls ontimeupdate="restrictAudio(this)">
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
</audio>
<script>
function restrictAudio(event) {
// Trying to stop the player if it goes above 10 second
if (event.currentTime < 10 || event.currentTime > 40) {
event.pause();
event.currentTime = 10
}
}
</script>
功能限制音频(事件){
//如果超过10秒,试图阻止玩家
如果(event.currentTime<10 | | event.currentTime>40){
事件暂停();
event.currentTime=10
}
}
在将音频文件插入页面之前,是否可以编辑音频文件?javascript具有.currentTime方法,该方法将其设置为10sI。我不认为这是可能的。至少这会很困难。只需在上传音频之前对其进行编辑。
var startTime = 10;
var endTime = 15;
// Get our audio (could also get an audio element from the DOM)
var audio = new Audio('http://www.tonycuffe.com/mp3/cairnomount.mp3');
// Must start before we can set the time
audio.play();
// Must make sure audio is ready
// see: http://stackoverflow.com/a/20240607/1968462
audio.addEventListener("canplay", function() {
audio.currentTime = startTime;
});
// Every 1000ms (1 second), we check if we've exceeded the bounds and if so, we
// set the time back to the end.
setInterval(function(){
if(audio.currentTime > endTime) {
audio.currentTime = startTime;
}
console.log(audio.currentTime);
}, 1000);
<audio controls ontimeupdate="restrictAudio(this)">
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
</audio>
<script>
function restrictAudio(event) {
// Trying to stop the player if it goes above 10 second
if (event.currentTime < 10 || event.currentTime > 40) {
event.pause();
event.currentTime = 10
}
}
</script>