简体   繁体   English

Audio.play()导致微小的延迟

[英]Audio.play() causes tiny lag

Problem: I have made a flappy-bird like game using Three.js. 问题:我使用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. 如果我移除声音,所有lagg都会消失。 The lagg only appears as the audio is played, not while the audio is playing. lagg仅在播放音频时出现,而不是在播放音频时出现。

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. 这很好用,但是出现了一个小小的lagg。

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. FPS:我还检查了audio.play()如何影响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): 我的FPS稳定在59左右。但是当我播放音频时,FPS会下降到20-30之间,这可能是造成微小延迟的原因(见图):

Audio.play() affecting FPS 影响FPS的Audio.play()

I checked FPS using this: 我用这个检查了FPS:

console.log(1/delta);

And also outputting "flapp" to the console when touching screen. 并且在触摸屏幕时也会向控制台输出“flapp”。

I hope someone has an explanation to this! 我希望有人对此有解释!

Best regards, Joakim 最好的问候,Joakim

The problem is that you use HTML5 audio for interactive sound effects. 问题是您使用HTML5音频进行交互式音效。 The API is not intended for this purpose. API不适用于此目的。 Instead, use the Web Audio based classes like THREE.Audio or THREE.PositionalAudio which allow sound effects without delay and appropriate timing. 相反,使用基于Web音频的类,如THREE.AudioTHREE.PositionalAudio ,它们可以在没有延迟和适当时间的情况下实现声音效果。

https://threejs.org/examples/#webaudio_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... 时序控制具有高精度和低延迟,允许开发人员编写能够准确响应事件的代码......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM