Limit audio playback to the specified range.

Let's say I have an audio file 90 seconds long.

I want to load this audio file for user playback, but the playback limit is between 10s-40.

What I am trying to achieve:

  • Audio starts at 10 seconds
  • When the sound ends, it resets to the 10 second mark
  • Audio ends at 40 seconds
  • Out of range audio not available
+3


source to share


3 answers


Had a similar task

The solution is this: this will cause the playback to jump to the beginning of the segment if someone tries to select an appearance, and also to do so at the end of the segment:



<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>

      

+2


source


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);

      

Example: http://jsfiddle.net/bn66s67q/1/

Please note that this is not a very good approach. The user has to download the entire file, not just the truncated part. You should strongly consider truncating the file. You could even do a truncation server with an audio editing library.



Also note that this is not accurate. I have added current time logging to the above example (view it in the JavaScript console). You will notice that you may be in second place. If you need precision, you can decrease the time interval.

This code works in the latest versions of Firefox, Chrome and IE (I haven't tested others).

+1


source


<script>
var audiofile = document.getElementById("myAudio");
 var currenttime=  audiofile.currentTime;
 currenttime=10;
 if(currenttime>39){currenttime=10;}
</script>

      

0


source







All Articles