Search code examples
androiddatasourcemedia-player

Can't set asset as datasource in the mediaplayer


I'm currently building a soundboard app as my first little Android app project. I saved a bunch of .mp3 files in the assets folder of my app and then dynamically created buttons based on the .mp3 files stored in there. In the tag of every button, I saved its corresponding .mp3 file name.

In the onClick() event of every button, I try to set the DataSource of a global MediaPlayer to the file from my assets. The FileDescriptor handles the openFd command flawlessly but the mediaPlayer can't set the DataSource.

The app just crashes, after executing that command. Here is the OnClickListener:

tempButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {                   
        mediaPlayer.release();
        String tag = v.getTag().toString();

        try {
            AssetFileDescriptor afd = getAssets().openFd(tag + ".mp3");
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            afd.close();

            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
});

The logcat prints the following crash when executing the setDataSource() method:

05-22 16:23:45.191 4505-4505/com.development.alo.dasunterboard E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.development.alo.dasunterboard, PID: 4505
    java.lang.IllegalStateException
        at android.media.MediaPlayer._setDataSource(Native Method)
        at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1133)
        at com.development.alo.dasunterboard.MainActivity$2.onClick(MainActivity.java:79)
        at android.view.View.performClick(View.java:5198)
        at android.view.View$PerformClick.run(View.java:21147)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

I took a look into the MediaPlayer.java because the crash seems to happen there. It looks like the FileDescriptor not valid.


Solution

  • you should not release() MediaPlayer before setting DataSource, but should reset() it. Replase mediaPlayer.release(); with mediaPlayer.reset();