gpt4 book ai didi

Android - 使 SoundPool 成为全局类? (适用于所有其他类(class))

转载 作者:行者123 更新时间:2023-11-30 03:47:00 25 4
gpt4 key购买 nike

基本上,我在 SurfaceView 上创建游戏,并且在我的主 CustomView 上有这些类:

private TitleScreen titleScreen;
private GameScreen gameScreen;
private PauseScreen pauseScreen;
private GameOverScreen gameOverScreen;

这些类中的每一个都有一个draw(Canvas canvas) 方法,当用户转到另一个屏幕时调用。但问题是,我有一个 SoundPlayer 类,其中包含我使用 SoundPool 的所有音效。它将用于所有这些类。实际上有没有一种方法可以让 SoundPlayer 只加载一次,然后在所有这些类中都可用?还是每次切换时都必须调用 release() 并调用构造函数?提前致谢。 :D

更新(已解决):

这就是我所做的。我创建了一个 SoundPlayer 类的实例:

public class SoundPlayerInstance {
private static SoundPlayer soundPlayerInstance;
private SoundPlayerInstance(){}

public static void createInstance(Context context){
soundPlayerInstance = new SoundPlayer(context);
}

public static SoundPlayer getInstance(){
return soundPlayerInstance;
}
}

在我的主视图中,在我做任何事情之前,我在我的构造函数中调用它:

SoundPlayerInstance.createInstance();

然后,在我的任何类(class)中,我都可以调用它来播放声音:

SoundPlayerInstance.getInstance().playSound();

我认为这不仅对此类情况有用,而且对想要实例化一个在所有其他类中都可用的类的开发人员(如我)也很有用。感谢 system32 回答我的问题。 :)

最佳答案

Is there actually a way that the SoundPlayer only loads once, then is available throughout these classes?

这是可能的。使 SoundPlayer 类成为单例。

public class SoundPlayer
{

private static SoundPlayer instance;

private SoundPlayer()
{
// Do some stuff
}

public static SoundPlayer getInstance()
{
if(instance == null)
instance = new SoundPlayer();

return instance;
}

}

要全局访问,只需调用SoundPlayer.getInstance()

关于Android - 使 SoundPool 成为全局类? (适用于所有其他类(class)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14844576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com