Playing audio induces slight delay

Issue: I created a game similar to Flappy Bird using Three.js. Every time I tap the screen, a flapping sound is triggered. However, playing this audio causes a slight lag in the game, making it less smooth. The lag only occurs when the audio is played and not while it is actually playing.

Audio Configuration: To set up the audio, I followed these steps:

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

Next, I load all audio files when the game starts (on button click):

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

Then, every time the screen is touched, I play the sound:

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

This setup works efficiently, but the slight lag persists.

Rendering: Here is how I configured the scene rendering:

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

var render = function ()
{

delta = clock.getDelta();

//All movements are based on speed * delta

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

FPS: I also assessed the impact of audio.play() on the FPS. My FPS remains stable at around 59. However, when I play the audio, it drops to between 20-30, likely causing the minor lag as shown in the image below:

Audio.play() affecting FPS

I measured the FPS using this:

console.log(1/delta);

I also checked for 'flapp' output in the console when touching the screen.

I am hopeful someone can provide an explanation for this issue!

Best regards, Joakim

Answer №1

The issue lies in using HTML5 audio for interactive sound effects, which is not the intended purpose of the API. It is recommended to utilize Web Audio based classes such as THREE.Audio or THREE.PositionalAudio for sound effects without delay and with proper timing.

For more information, please visit:

To delve deeper into this topic, refer to the following guide, which emphasizes:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to specify a unique body parser for a specific route in Express

Currently, I am utilizing express version 4 in my project. Within my server.js file, I have integrated the express.json() middleware to handle JSON data. require('dotenv').config(); const express = require('express'); const cors = requi ...

What is the most effective way to utilize zoom with an Orthographic projection?

I'm attempting to utilize THREE.OrbitControls for zooming in an orthographic projection, but I'm not achieving the desired outcome. I believe it may be possible to adjust the viewSize that is multiplied by left, right, top, and bottom to achieve ...

Issue with Bootstrap carousel - the carousel.on method is not recognized

I have implemented a standard Bootstrap carousel in my project: <div id="myCarousel" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"> ...

Updates to props values are not being reflected in the React js application running on the webpack

I keep facing an issue where I have to restart the webpack server every time I try to pass or update props values from parent to child components. It's frustrating that the props values are not updating even after saving the file. Take a look at my p ...

SkeletonHelper remains unseen in the rendered scenes

I'm attempting to showcase a Three JS Skeleton with the use of SkeletonHelper. As stated in this response, the SkeletonHelper() function requires the root bone. I've followed these instructions, but unfortunately, the skeleton is not appearing o ...

What is the process by which JavaScript evaluates the closing parenthesis?

I'm currently working on a calculator project that involves evaluating expressions like (5+4). The approach I am taking is to pass the pressed buttons into an array and then create a parse tree based on the data in that array. One issue I'm faci ...

Is there a way to automatically refresh a webpage whenever there are changes

Currently, I have a webpage that operates like a reverse auction, complete with a javascript countdown timer that tracks the time remaining in the auction. Once the timer reaches zero, the auction ends and the page automatically refreshes. While everythin ...

Determine the difference between dates using Angular 2's array filtering function

Here's a way to get the current time in seconds: let currentTimeInSeconds = new Date().getTime() / 1000; I have an array containing objects with an expirationDate property that returns expiration time in seconds. I can find the bills that have expir ...

v-show is not functioning properly

After clicking the button, I notice that even though the array shows[] changes (as indicated by Vue's chrome plugin), the character 'a' remains on the page. However, characters 'b' and 'c' do not appear at all. ...

Is there a way to modify my code to restrict users from liking a post multiple times?

I am currently working on a like system and I have made some progress. However, I am struggling to make it so that the likes only increment once. Does anyone have any insights or suggestions on how to achieve this? I have considered using session variables ...

"Having trouble implementing sorting functionality on a click event in a React application with Material-UI table

Default behavior displays data in ascending order. Clicking on the table header should toggle between descending and ascending orders. Load Data in ascending order -> On click, change to descending order -> Again on click, change to ascending -> ...

Where have all the setters gone for CGPDF<...>?

Is there a way to generate custom PDF objects using CGPDF, such as a PDF-dictionary with parameters needed by a specialized PDF producer/consumer/viewer? Or must I create my own parser and manually add new objects like trailers, xrefs, etc. to the PDF file ...

Looking for assistance in setting up a personalized slideshow to automatically play on its

Recently, I have taken responsibility for a project that was initiated by someone else. The website contains a customized slideshow on its homepage. To meet the client's requirements, I have already made some alterations to the appearance and feel of ...

Transforming ng-if state and img src dynamically in an Angular (1) directive

I've recently been exploring different ways to optimize my code, specifically by utilizing a directive instead of the standard img tags. I'm aiming to dynamically modify the ng-if state and the src based on the input value in the directive. Curr ...

Fullcalendar inaccurately displays events

I recently integrated fullcalendar into my website, but I've come across a strange bug. The event is set up correctly with all the necessary information, yet when the calendar loads, it appears in the wrong position and for the wrong duration. However ...

Leveraging regular expressions for image domains within NextJS next.config.js

Is it possible to use regex in next.config.js to allow image domains? Giphy uses different numbers for its endpoints (e.g. media0.giphy.com, media2.giphy.com), but my regex isn't working and I'm seeing this error message: hostname "media0.gi ...

What is the process of adding a unique model to three.js?

Despite trying numerous solutions to a common problem, I am still unable to import my 3D model in Three.js using the following code: <script src="https://threejs.org/build/three.min.js"></script> <script src="https://cdn.rawgi ...

Create an array by copying elements from another array object

My goal is to merge the data from two arrays, array1 and array2, into a new array called array3. Here's how I want it structured: array 1 objects: userName, userId array 2 objects: userId, msg I aim to obtain an array3 consisting of: userId, userNa ...

The issue with displaying Fontawesome icons using @import in CSS-in-JS was not resolved

I recently changed how I was importing Fontawesome icons: src/App.css @import "@fortawesome/fontawesome-free/css/all.css";` After shifting the @import to CSS-in-Js using emotion: src/App.js // JS: const imports = css` @import "@fortawes ...

Tips for effortlessly enlarging an element

When you click on "#sidebarnav>li", the following happens: 1) The second child of it - <ul> element will expand and its class toggles between "collapse" and "collapse in". 2) "#sidebarnav>li" will receive the "active" class. 3) The "aria-ex ...