MediaPlayer - java.io.FileNotFoundException: No content provider

帅比萌擦擦* 提交于 2019-12-07 04:01:30

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/46080969/mediaplayer-java-io-filenotfoundexception-no-content-provider

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