MediaPlayer - java.io.FileNotFoundException: 没有内容提供者

MediaPlayer - java.io.FileNotFoundException: No content provider

我写一个 mp3 播放器已经有一段时间了,但是由于某些原因这个异常:

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

每次我尝试播放 任何 歌曲时都会弹出。

我检索歌曲路径的方式是:

file.getAbsolutePath()

其中 file 是一个文件实例。我播放这首歌的方式是:

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

其中 this 是对 class 实例的引用,它扩展了 Service.

有什么想法吗?

据推测,currentTrack 有一个 File 对象。如果是这样,请将 Uri.parse(currentTrack.getPath()) 替换为 currentTrack.getUri(),其中您将 getUri() 实现为 return FileUri.fromFile() 的值。

这解决了您眼前的问题,即您创建了一个无效的 Uri,因为它没有方案。它还可以让您处理将来可能需要的 Uri 非文件类型(例如 content Uri 值)。

如果您使用的是牛轧糖或更高版本,则必须使用 Content Provider

在 XML 资源文件夹中创建一个 XML 文件(例如 file_provider_paths.xml):

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

现在在您的 ApplicationManifest.xml 中定义一个提供程序,在应用程序节点中添加此提供程序:

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

现在获取共享文件 URI,并在您的应用程序中需要的地方使用它。

Uri sharedFileUri = FileProvider.getUriForFile(this, <your provider auhtority>, sharedFile);