Android Asset Manager无法从资产目录加载WAV文件资产

时间:2019-05-26 20:38:12

标签: java android android-assets android-assetmanager

我要在Android的资产管理器的帮助下加载一些wav文件。不幸的是,每次我尝试这样做时,都会出现以下错误

  

java.io.FileNotFoundException:找不到audio-file.wav

我想将以下资产添加到Android声音池中。

这是我的应用程序设置的图像。

Application IDE Set up

我的代码

google

片段

add()

此方法引发一个toMainActivity.add(new NewMission...

public class MyActivity extends AppCompatActivity {

  protected abstract Fragment createFragment();

  @LayoutRes
  protected int getLayoutRes() {
    return R.layout.activity_fragment;
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(getLayoutRes());

    FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragment_container);
    if (fragment == null) {
      fragment = new MyActivityFragment();
      fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
    }
  }

}

这行正好

    public class MyActivityFragment extends Fragment {

       private static final String TAG = "MyFragment";
       private static final String SOUNDS_FOLDER = "sample_sounds";
       private static final int MAX_SOUNDS = 5;


    private final AssetManager mAssetManager;

      private final List<Integer> sounds = new ArrayList<>();
      private SoundPool mSoundPool; 

      @Override
      public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        this.mAssetManager = getActivity().getAssets();
        this.loadAssets();
        mSoundPool = this.buildSoundPool();
      }

      @Override
      public void onDestroy() {
        super.onDestroy();
        mSoundPool.release();
      }


  private SoundPool buildSoundPool() {
    SoundPool.Builder builder = new SoundPool.Builder();
    builder.setMaxStreams(MAX_SOUNDS);
    builder.setAudioAttributes(new AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_MEDIA)
        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
        .build());
    return builder.build();
  }

  private void loadAssets() {
    try {
      String[] soundNames = mAssetManager.list(SOUNDS_FOLDER);
      for (String soundName : soundNames) {
        sounds.add(load(soundName));
      }
    } catch (IOException ioe) {
      Log.e(TAG, "Could not list assets");
    }
  }

   private int load(String soundName) throws IOException {
      AssetFileDescriptor afd = mAssetManager.openFd(soundName);
      int soundId = mSoundPool.load(afd, 1);
      return soundId;
   }
}

我浏览了与此问题相关的其他帖子,但是最近的帖子至少3岁。我不知道我在做什么错。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

IIRC,list()返回资产目录中项目的名称。它不会返回这些项目的 paths

尝试更换:

AssetFileDescriptor afd = mAssetManager.openFd(soundName);

具有:

AssetFileDescriptor afd = mAssetManager.openFd(SOUND_FOLDER+"/"+soundName);