MediaPlayer does not play sound file in the assets folder

0

How do I play sound in the assets folder in Android Studio? When the sound is in the raw folder it performs normal, but I need to run in the assets folder, to pass the name dynamically, below is the example, but it still does not work.

public void playSom() {
    try {
        System.out.println("Iniciando Som...");
        if (mp01.isPlaying()) {
            mp01.stop();
            mp01.release();
            mp01 = new MediaPlayer();
        }

        AssetFileDescriptor assets = getAssets().openFd("errou_1.mp3");
        mp01.setDataSource(assets.getFileDescriptor(), assets.getStartOffset(), assets.getLength());
        //mp01.prepare();
        mp01.prepareAsync();
        mp01.setVolume(1f, 1f);
        //mp01.setLooping(true);
        mp01.start();
        assets.close();

        if (mp01.isPlaying()) {
            System.out.println("Tocando Som ( OK )...");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
    
asked by anonymous 03.02.2017 / 13:58

1 answer

1

The problem is that start is done before the player is ready:

mp01.prepareAsync();
mp01.setVolume(1f, 1f);
//mp01.setLooping(true);
mp01.start();

The prepareAsync() method, being asynchronous, returns immediately, enabling mp01.start(); to run before the player is ready.

Use the mp01.prepare(); synchronous method or use a MediaPlayer.OnPreparedListener to execute start.

Note: The beginning of the errou_1.mp3 exists and is placed in a folder named assets within the main folder.

You can use the files in the raw folder, by name, like this:

int soundResId = getResources().getIdentifier("errou_1", "raw", getPackageName());
MediaPlayer mediaPlayer=MediaPlayer.create(this,soundResId);
mediaPlayer.start();
    
03.02.2017 / 15:46