How to play selected part of an audio file in JavaScript

In this JavaScript tutorial, we gonna learn how to play a selected portion of an audio in JavaScript. I have posted some useful tutorial to work with HTML5 audio in JavaScript like:
How to Play Audio After Few Seconds or Delay in JavaScript
How to set audio playing time to starting position in JavaScript
Pause or Stop Audio After Few Seconds in JavaScript
To play selected part of an audio file in JavaScript you need to use the following:

  • audio.currentTime
  • audio.play()
  • audio.pause()

Here “audio” is a variable and we are appendingĀ currentTime, play method and pause method

Play Selected Part of an Audio File in JavaScript

Logic:

Let’s assume you have an audio element. Just append currentTime to your audio to set the current time as per your choice. Then simply start the audio with play() method.

Now the next thing you need to do is, you have to pause the audio on a specific time delay.

For example, let’s assume you have an audio file and you have to play a particular portion ( 50th second to 56th second ) of this audio file.

You can use it like this,

if(audio.currentTime>56){
audio.pause();
}

But oh no! you have to check for the current time every second so that JavaScript can detect the if statement is true or false.

Here is the solution

function settime(){
	var audio= document.getElementById("myaudio");
	audio.currentTime=50;
	audio.play();
	console.log(audio.currentTime); // this is to check the currentTime in the console log
       
// the below setInterval is to check the currentTime is greater than 56 or not in every 1 second
	setInterval(function(){
		if(audio.currentTime>56){
			audio.pause();
				}
			},1000);
		}

This is the audio element in HTML5

<audio id="myaudio" src="filename.mp3"></audio>

Just run the whole above JavaScript code in a function when the use clicks on a particular button using onclick.

You can also read,

HTML5 Video Volume Controller in JavaScript with Slider

Forward and backward HTML5 video player with left and right arrow key in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *