'Audio.play() causes tiny lag

Problem: I have made a flappy-bird like game using Three.js. Everytime I tap the screen, a "flap"-sound is played. However playing this audio causes a tiny lagg, which makes the game less smooth. If I remove the sound, all lagg disappears. The lagg only appears as the audio is played, not while the audio is playing.

Audio set-up: First I set up the audio like this:

var soundFly = new Audio();
soundFly.src = "https://dl.dropbox.com/s/tj7mxg26egzo4zx/flap.wav?dl=0";
soundFly.preload = "auto";

Next I load all audio upon starting the game (on button click):

function loadAudio()
{
soundFly.play().then(function () {
   soundFly.pause()
   }).catch(function (e) {
            console.log("soundFly - " + e)
            });           
};

Then, everytime I touch the screen, I play the sound:

this.soundFly.play().catch(function (e)     {
    console.log("soundFly - " + e)
})

This works great, but the tiny lagg appears.

Rendering: This is how I set up the rendering of the scene:

var clock = new THREE.Clock();
var delta=0;
clock.start(); //makes rendering timedependent

var render = function ()
{

delta = clock.getDelta();

//All movement is set using speed*delta

requestAnimationFrame(render);
renderer.render(scene, camera);
};

FPS: I have also checked how the audio.play() affects the FPS. My FPS is steady at about 59. But when I play the audio, the FPS drops to between 20-30, which probably is what causes the tiny lagg (see picture):

Audio.play() affecting FPS

I checked FPS using this:

console.log(1/delta);

And also outputting "flapp" to the console when touching screen.

I hope someone has an explanation to this!

Best regards, Joakim



Solution 1:[1]

The problem is that you use HTML5 audio for interactive sound effects. The API is not intended for this purpose. Instead, use the Web Audio based classes like THREE.Audio or THREE.PositionalAudio which allow sound effects without delay and appropriate timing.

https://threejs.org/examples/#webaudio_timing

Also read the following guide for more information. It says:

Timing is controlled with high precision and low latency, allowing developers to write code that responds accurately to events...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mugen87