有没有办法使用libgdx一次加载整个目录?

时间:2015-07-25 19:20:36

标签: java android json libgdx save

我正在使用libgdx来制作Android游戏,我正在添加声音fx,我想知道是否有任何方法可以同时加载目录中的所有声音文件而不是一个一个人。

我将它们加载到这样的资产管理器中,我似乎找不到任何方法来加载整个文件夹。

loadassets.load(“directory / folder / filename.mp3”,Sound.class);

1 个答案:

答案 0 :(得分:2)

就在两天前,我写了一个小实用程序类来做到这一点。不仅适用于声音文件,也适用于任何类型的资源。

public class AssetFinder {

    private AssetManager assetManager;
    private FileHandleResolver resolver;

    public class AssetDescriptor {
        public String folder;
        public Class<?> assetType;

        public AssetDescriptor(String folder, Class<?> assetType) {
            this.folder = folder;
            this.assetType = assetType;
        }
    }

    private Array<AssetDescriptor> assets = new Array<AssetDescriptor>();

    public AssetFinder(AssetManager assetManager, FileHandleResolver resolver) {
        this.assetManager = assetManager;
        this.resolver = resolver;

        assets.add(new AssetDescriptor("music", Music.class));
        assets.add(new AssetDescriptor("sound", Sound.class)); // You could remove all but this one
        assets.add(new AssetDescriptor("skin", Skin.class));
        assets.add(new AssetDescriptor("texture", Texture.class));
        assets.add(new AssetDescriptor("atlas", TextureAtlas.class));
        assets.add(new AssetDescriptor("font", BitmapFont.class));
        assets.add(new AssetDescriptor("freetype", FreeTypeFontGenerator.class));
        assets.add(new AssetDescriptor("effect", ParticleEffect.class));
        assets.add(new AssetDescriptor("pixmap", Pixmap.class));
        assets.add(new AssetDescriptor("region", PolygonRegion.class));
        assets.add(new AssetDescriptor("model", Model.class));
        assets.add(new AssetDescriptor("level", TiledMap.class));
    }

    public void load() {
        for (AssetDescriptor descriptor : assets) {
            FileHandle folder = resolver.resolve("").child(descriptor.folder);
            if (!folder.exists()) {
                continue;
            }

            for (FileHandle asset : folder.list()) {
                assetManager.load(asset.path(), descriptor.assetType);
            }
        }
    }
}

使用它很简单,就像这样:

FileHandleResolver resolver = new InternalFileHandleResolver();
AssetManager assets = new AssetManager(resolver);
AssetFinder assetFinder = new AssetFinder(assets, resolver);
assetFinder.load();
assets.finishLoading();