Android MediaPlayer gives null exception

2019-08-14 09:58发布

问题:

Can someone help me with this strange issue, I want to play an audio file from SDCard , this is the code,I know that this is the right file path, but MediaPlayer gives me a null exception. Any help will be appreciated!

File file = new File(android.os.Environment.getExternalStorageDirectory()+"/rockstar.mp3");
MediaPlayer m = MediaPlayer.create(getApplicationContext(), Uri.fromFile(file));
m.start();

This is stacktarce

java.lang.NullPointerException

回答1:

Are you not missing .getAbsolutePath()?

File file = new File(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/rockstar.mp3");


回答2:

Be sure to add the right permission in your AndroidManifest.xml, which is <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />. Log your path uri in LogCat to see if everything is correct, and start your media player like this :

   MediaPlayer player = new MediaPlayer();
   player.setDataSource("mnt/sdcard/music.mp3");
   player.prepare();
   player.start();


回答3:

Try this:

String path = Environment.getExternalStorageDirectory().getAbsolutePath();
path+="/music.mp3"
mp.setDataSource(path)
mp.prepare();
mp.start();