Search code examples
javaandroidandroid-studioandroid-mediaplayer

Error creating Media Player; Java, Android Studio


Well i know, that there are 2 results of MediaPlayer.create() function: created stream or null, and in this case i get the second one result. Got some thoughts about file path, but still don't know where i'm wrong. (Trying to play a random track from assets folder). Thanks in advance!

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button play36 = (Button)findViewById(R.id.threesix);


    String[] listOfFiles = new String[0];
    try {
        listOfFiles = getAssets().list("");
    } catch (IOException e) {
        e.printStackTrace();
    }

        int itemIndex = (int) (Math.random() * listOfFiles.length);
        String file = listOfFiles[itemIndex];
        String filePath = "file:///android_asset/".concat(file);
        Uri uri = Uri.parse(filePath);
        final MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this, uri);

        play36.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
            }
        });

}

Solution

  • I tried your code and i too got that exception i have modified the code. You can try it. It is working on my device

                        String[] listOfFiles = new String[0];
                        try {
                            listOfFiles = getAssets().list("");
                            //  int itemIndex = (int) (Math.random() * listOfFiles.length);
                            int itemIndex = 1;
                            String file = listOfFiles[itemIndex];
                            AssetFileDescriptor afd = null;
                            afd = getAssets().openFd(file);
    
                            MediaPlayer mediaPlayer = new MediaPlayer();
                            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    
                            mediaPlayer.prepare();
                            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                @Override
                                public void onPrepared(MediaPlayer mediaPlayer) {
                                    mediaPlayer.start();
                                }
                            });
    
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
    

    NOTE: I have commented the random itemIndex because assets folder contain other things too. Like i had these in my folder so mind this thing.

    enter image description here

    For this you can limit the random number generation to number of your audio files in assets folder.