Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MediaPlayer - java.io.FileNotFoundException: No content provider

I've been writing an mp3 player for quite some time, but for some reason this exception:

W/MediaPlayer: Couldn't open /storage/emulated/0/Music/generic music file.mp3: java.io.FileNotFoundException: No content provider: /storage/emulated/0/Music/generic music file.mp3

keeps popping up every time I try to play any song.

The way I retrieve path to a song is:

file.getAbsolutePath()

where file is a File instance. And the way I play the song is:

try {
    mediaPlayer = MediaPlayer.create(this, Uri.parse(currentTrack.getPath()));
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            nextTrack();
        }
    });
} catch (Exception ex) {
    ex.printStackTrace();
}

where this is a reference to an instance of a class, which extends Service.

Any ideas?

like image 688
Andrej Korowacki Avatar asked Sep 06 '17 17:09

Andrej Korowacki


2 Answers

Presumably, currentTrack has a File object. If so, replace Uri.parse(currentTrack.getPath()) with currentTrack.getUri(), where you implement getUri() to return the value of Uri.fromFile() for the File.

This solves your immediate problem, which is that you have created an invalid Uri, as it has no scheme. It also sets you up to deal with Uri types that are not files (e.g., content Uri values) that you may wind up needing in the future.

like image 83
CommonsWare Avatar answered Oct 20 '22 21:10

CommonsWare


This issue occurs in Nougat or higher version if you are using nougat or higher version you have to use Content Provider.

Create an XML file (for example file_provider_paths.xml) in XML resources folder:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="shared" path="shared/"/>
</paths>

Now define a provider in your ApplicationManifest.xml, add this provider inside application node:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="<your provider authority>" //com.domainname.appname.fileprovider
    android:exported="false"
    android:grantUriPermissions="true">
  <meta-data
      android:name="android.support.FILE_PROVIDER_PATHS"
      android:resource="@xml/file_provider_paths"/>
</provider>

Now get the shared file URI, and use it in your application where you need it.

Uri sharedFileUri = FileProvider.getUriForFile(this, <your provider auhtority>, sharedFile);
like image 39
Prashant Kumar Sharma Avatar answered Oct 20 '22 21:10

Prashant Kumar Sharma