首页 > 解决方案 > 从 Assets 文件夹中读取声音(使用 android nexus 5 模拟器,但不在我的手机上)

问题描述

我成功地使用 Android Emulator 运行了我的功能。Assets 文件夹很好识别,所有声音文件都在我的 Array allSounds 中。

但是当我尝试在我的手机上使用 ADB 运行我的 apk 时,我在 Assets 中的声音文件夹是空的。此功能在主 Activity 上。

你有什么想法来理解我的问题吗?

谢谢 !!

 public void playRandom(View view) throws IOException {
        Resources res = getResources(); //if you are in an activity
        AssetManager aMan = res.getAssets();
        sounds = new ArrayList<>();
        String path = "sounds/";

        String folderNames[] =  aMan.list(path);
       // TextView debug = (TextView) findViewById(R.id.debug);
        //Evite de reCall la fonction si les sons sont déjà dans l'Array allSounds[]
        if (!flagDoNotRepeat) {
            for (String folderName : folderNames) {
                String[] fileNames = getAssets().list(path + folderName + "/");
                for (String file : fileNames) {
                    allSounds.add(path + folderName + "/" + file);
                    //debug.append("\n" + path + folderName + "/" + file);
                    flagDoNotRepeat = true;
                }
            }
        }
        m = new MediaPlayer();
            try {
                if (m.isPlaying()) {
                    m.stop();
                    m.release();
                    m = new MediaPlayer();
                }

                AssetFileDescriptor descriptor = aMan.openFd(allSounds.get(new Random().nextInt(allSounds.size())));
                m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
                descriptor.close();

                m.prepare();
                m.setVolume(1f, 1f);
                m.start();

            } catch (Exception e) {
                e.printStackTrace();
            }
    }

编辑:我解决了我的问题:

 am = getAssets();

    String path = "sounds";

    String folderNames[] = new String[0];
    try {
        folderNames = am.list(path);
    } catch (IOException e) {
        e.printStackTrace();
    }
    // TextView debug = (TextView) findViewById(R.id.debug);
    //Evite de reCall la fonction si les sons sont déjà dans l'Array allSounds[]
    if (!flagDoNotRepeat) {
        for (String folderName : folderNames) {
            String[] fileNames = new String[0];
            try {
                fileNames = am.list(path + "/" + folderName);
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (String file : fileNames) {
                allSounds.add(path + "/" + folderName + "/" + file);
                //debug.append("\n" + path + folderName + "/" + file);
                flagDoNotRepeat = true;
            }
        }
    }

标签: androiddirectoryassets

解决方案


推荐阅读