如何确保指定声音只有 1 个实例在循环以及如何阻止它循环?

我目前正在开发一款游戏,在播放器更新方法中,我希望脚步Sound在玩家行走时开始循环,我希望它在玩家停止行走时停止循环。但是,我无法弄清楚如何确保只有 1 个实例在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();

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


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


一只斗牛犬
浏览 69回答 1
1回答

largeQ

假设你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(long) 来停止声音。也许stop您正在使用的版本不起作用,或者它等待当前循环完成?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java