Android的MediaPlayer的给空例外(Android MediaPlayer gives

2019-10-16 17:28发布

有人可以帮我这个奇怪的问题,我想从SD卡播放音频文件,这是代码,我知道这是正确的文件路径,但MediaPlayer的给了我一个空例外。 任何帮助将不胜感激!

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

这是stacktarce

显示java.lang.NullPointerException

Answer 1:

你是不是缺少.getAbsolutePath()

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


Answer 2:

一定要添加正确的权限在AndroidManifest.xml ,这是<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 登录logcat的路径中的URI,看看是否一切正常,并启动媒体播放器这样的:

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


Answer 3:

尝试这个:

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


文章来源: Android MediaPlayer gives null exception