Android MediaPlayer gives null exception

六眼飞鱼酱① 提交于 2019-12-11 07:38:55

问题


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();


来源:https://stackoverflow.com/questions/10634769/android-mediaplayer-gives-null-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!