Mediaplayer does not play existing sound file in Assets folder

Asked

Viewed 136 times

0

How do I run the sound in the Assets folder in Android Studio? When the sound is in the raw folder runs normal, but I need to run in the Assets folder, to pass the name dynamically, below is the example, but it still doesn’t 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();
    }
}

1 answer

1


The problem is that the start before the player be prepared:

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

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

Use the synchronous method mp01.prepare(); or use a Mediaplayer.Onpreparedlistener to run the start.

Note: I assume that the file errou_1.mp3 exists and is placed in a folder with the name assets inside the briefcase main.

It is possible to use existing files in the folder raw, through the name, in this way:

int soundResId = getResources().getIdentifier("errou_1", "raw", getPackageName());
MediaPlayer mediaPlayer=MediaPlayer.create(this,soundResId);
mediaPlayer.start();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.