I'm writing a basic android mp3 player app that uses the MediaPlayer app to play an mp3 file stored locally on an Android phone.
However, whenever I try calling MediaPlayer.create()
i get a java.io.FileNotFoundException
.
I've checked to make sure that the mp3 is in the correct path and I've tried running this on both an emulated Android and my own phone but I keep getting the same error.
Here's my onCreate function where I'm having the problem:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() +
"/Download/sam_stone.mp3");
med = MediaPlayer.create(getApplicationContext(), uri);
}
Here's the error I'm getting:
java.io.FileNotFoundException: /storage/emulated/0/Download/sam_stone.mp3 (Permission denied) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(FileInputStream.java:146) at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1088) at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1067) at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1009) at android.media.MediaPlayer.setDataSource(MediaPlayer.java:967) at android.media.MediaPlayer.create(MediaPlayer.java:874) at android.media.MediaPlayer.create(MediaPlayer.java:851) at android.media.MediaPlayer.create(MediaPlayer.java:830) at hn.mediaplayer.MainActivity.onCreate(MainActivity.java:48) at android.app.Activity.performCreate(Activity.java:6662) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6077) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
You have to add READ_EXTERNAL_STORAGE
permission in manifest.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
and from marshmallow and above you have to request from the users for Dangerous permission.