How to instantly play an audio clearly using javascript without any lag?

I am developing a Javascript based app in which I use a clapping sound whenever a user clicks a button. The sound must play as soon as the user clicks the button(There should be no lag). I recorded the sound using audacity and saved it in wav format. Initially there was a lag before clap sound and I could hear the sound clearly when clicked on the button but a bit late as there is a lag before the sound as I have mentioned (You can see it in the picture below).

The wav sound before deleting the lag

I am not interested in the lag before the sound as I want the user to hear the sound as soon as he press the button. So I removed the lag in front of the clap in audacity as shown below.

After removing the lag in front of the clap

The sound was again saved in wav format and I can hear the sound clearly when played in audacious and winamp. But when I click on the button in the app when it is opened in a browser the clap sound became very mild as if I cannot hear that at all. I am really confused as I am not sure whether the problem is related to the file format or the javascript. Is there any way to play the sound clearly as soon as a button is clicked using javascript?

[updated part]

I am really sorry. There was a bug in my code. I set the initial time of the audio to 0.05 which caused the problem.

tapSound.currentTime=0.05;
tapSound.play();

Now that I can hear the sound clearly but there is still a lag before the sound everytime I click the button.

This is the javascript code that I have

var tapSound=new Audio();
tapSound.src="sounds/tap.wav";
tapSound.preload='auto';
$(".refresh, .backspace, .home, .pause, .about, .backbutton").on('click',function () {
tapSound.currentTime=0.01;
tapSound.play();
});

Upvotes: 3

Views: 4925

Answers (1)

rcpinto
rcpinto

Reputation: 4318

You need to set the preload property of your Audio object to 'auto':

var audio = new Audio();
audio.src = "yourfile";
audio.preload = 'auto';

This code must be executed when you load your page, not when you click the button. When you click the button, just call the play() method for the audio object.

Upvotes: 3

Related Questions