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

标签 android global-variables soundpool

基本上,我在 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/

相关文章:

java - 如何实现实时EditText格式化?

c++ - std::cout 是否保证被初始化?

javascript - jQuery - 使全局变量可用于多个插件

android - 音频播放结束时发生咔嗒声。

android - 如何停止 SoundPool 中的所有声音?

android - 声音池未执行 “OnLoadComplete”

java - 来自 RSS 的图像 URL

android - 以编程方式删除所有联系人

android - jenkins 如何根据 git commit 消息中的关键字执行特定命令?

php - 如何在php中取消设置全局变量?