使用LibGDX的AssetsManager时,我实现了一个AssetsManager来管理Sounds,并使其成为全局的。这些文件都位于
中../data/sounds/.*
(example: ../data/sounds/buttons/buttonl.mp3)
然后我将声音文件加载到管理器中,然后包含一些代码来播放这些声音。代码如下:
public final class Sounds {
private static HashMap<String, HashMap<String, String>> entries = new HashMap<String, HashMap<String, String>>();
private static HashMap<String, String> currentPackage = new HashMap<String, String>();
public static Sound sound;
public Sounds() {
addPath(
"Main",
"bgm", "data/sounds/main/title.mp3",
"buttonl", "data/sounds/buttons/buttonl.mp3",
"buttonh", "data/sounds/buttons/buttonh.mp3");
//... More paths with more sound assets
}
public static boolean addPath(String packageName, String... args) {
if(!entries.containsKey(packageName)) {
entries.put(packageName, new HashMap<String, String>());
for(int i = 0; i < args.length; i ++)
entries.get(packageName).put(args[i], args[++i]);
return true;
}
return false;
}
public static void loadSoundAssets(String packageName) {
for(String str : entries.get(packageName).values())
s_manager.load(str, Sound.class);
s_manager.finishLoading();
}
public static boolean play(String file) {
if(currentPackage.containsKey(file)) {
sound = s_manager.get(file, Sound.class);
sound.play();
return true;
}
return false;
}
}
使用
在更高级别中创建Sound类之后public class Game implements ApplicationListener{
public Sounds gameSounds = new Sounds();
public Screen currentScreen = new MainMenuScreen();
//... More class variables and methods
public void render() {
currentScreen.update();
}
}
当我打电话
时出现问题public class MainScreen() extends Screen {
public MainScreen() {
Sounds.loadSoundAssets("Main");
//... More constructor variables and methods
}
//... Class variables and methods
public void update() {
if(s_manager.update()) {
if(play.getBoundingRectangle().contains(x, y))
Sounds.play("buttonl");
}
}
}
s_manager.update()返回true,但它会尝试播放声音文件“buttonl”并抛出此错误:
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Asset not loaded: buttonh
at com.badlogic.gdx.assets.AssetManager.get(AssetManager.java:121)
at device.sounds.Sounds.play(Sounds.java:146)
at game.screens.MainMenuScreen.update(MainMenuScreen.java:63)
at menu.StateManager.render(StateManager.java:89)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:190)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:110)
我应该如何使用AssetsManager来修复此加载/播放问题?我想使用AssetsManager,但目前我的解决方案是使用
sound = Gdx.audio.newSound(Gdx.files.internal(currentPackage.get(file)));
答案 0 :(得分:1)
我相信在你的play方法中,你在key上调用AssetManager.get而不是currentPackage中的值。我认为正确的游戏方法是:
public static boolean play(String file) {
if(currentPackage.containsKey(file)) {
sound = s_manager.get(currentPackage.get(file), Sound.class);
sound.play();
return true;
}
return false;
}