简体   繁体   中英

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();
}

Did You try this?

 MediaPlayer mediaPlayer = null;

    public void playSound(final Context context, final String fileName) {
        mediaPlayer = new MediaPlayer();
        try {
            AssetFileDescriptor afd = context.getAssets().openFd(fileName);
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            afd.close();
            mediaPlayer.prepare();
        } catch (final Exception e) {
            e.printStackTrace();
        }
        mediaPlayer.start();
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM