Search code examples
javaandroidmedia-player

How to play a WAV file loaded from Assets folder in Android?


I'm trying to play a .wav audio in Android from assets folder.

The problem is that there is no error but the audio isn't playing.

Here's my code

AssetFileDescriptor afd = null;
try {
   afd = getAssets().openFd("success.wav");
   player = new MediaPlayer();
                        player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
   player.setLooping(false);
   player.prepare();
   player.start();
} catch (IOException e) {
    e.printStackTrace();
}

Solution

  • Your code is ok, i checked, its working.

    1. Please ensure the \assets folder is placed correctly(\app\src\main\assets)
    2. Check your device volume level.
    3. Play success.wav in PC media player and ensure it is audible.

    Note: Using device volume controls:

    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    

    If your app is media related, use setVolumeControlStream API at your onResume() of activity or fragment and use device volume hard keys to increase/decrease volume. This set the application to only modify stream_music volume /media volume, otherwise it will modifiy ring volume. Ref:https://developer.android.com/guide/topics/media-apps/volume-and-earphones