我如何确保只有1个指定声音的实例是循环的,以及如何阻止它循环



我目前正在从事游戏,在玩家更新方法中,我希望脚步Sound在玩家走路时开始循环,我希望当玩家停止步行时它停止循环。但是,我在弄清楚如何做到的情况下难以确定Sound的一个实例正在循环。

进行澄清:我说的是gdx.audio.Sound类。这就是我的代码当前的样子:

//Sets the footstep sound. i.e. it changes to a grass soundfile when you walk on grass.
String footstepsFilePath = gameMap.getTileSoundFilePath(rect);
setFootsteps(Gdx.audio.newSound(Gdx.files.internal(footstepsFilePath)));
//velocity is the speed at which the player is going in the x or y direction.
if(velocity.y != 0 || velocity.x != 0) footsteps.loop();
if(velocity.y == 0 && velocity.x == 0) footsteps.stop();

结果:一旦玩家开始移动,脚步声的大量实例就开始循环。当玩家停止移动时,所有人都将继续循环。第一部分是出于明显的原因,但是我无法弄清楚如何确保只有1个实例正在循环。但是在第二部分中,我不确定为什么不所有的脚步实例都停止循环,因为这是stop()上的文档说:

停止播放此声音的所有实例。

假设您经常检查if(velocity.y != 0 || velocity.x != 0),您确实会启动许多循环。诀窍是检查"玩家是否在移动?而不是仅仅是"播放器移动"。

一种简单的方法是设置布尔标志:

//Sets the footstep sound. i.e. it changes to a grass soundfile when you walk on grass.
String footstepsFilePath = gameMap.getTileSoundFilePath(rect);
setFootsteps(Gdx.audio.newSound(Gdx.files.internal(footstepsFilePath)));
boolean isMoving = false;
//velocity is the speed at which the player is going in the x or y direction.
if((velocity.y != 0 || velocity.x != 0) && !isMoving) {
    isMoving = true;
    footsteps.loop();
}
if((velocity.y == 0 && velocity.x == 0) && isMoving) {
    footsteps.stop();
    isMoving = false;
}

我不确定为什么stop在您的情况下不起作用。但是,其他两个loop过载状态的文档

您需要使用返回的ID通过呼叫停止(长(来停止声音。

也许您使用的stop版本不起作用,或者它等待当前循环完成?

最新更新