访问flutter资源时出现File not Found异常

Gan*_*ari 5 java filenotfoundexception dart flutter

我正在尝试编写一个插件来播放存储在 flutter 包的 asset 文件夹中的音频文件,并且已经这样做了

if(call.method.equals("playMusic"))
{
    Log.d(TAG, "onMethodCall: play music function called");

    String fileLocation = call.argument("file");
    Log.d(TAG, "onMethodCall: file requested is "+fileLocation);
    AssetManager assetManager = registrar.context().getAssets();
    String key = registrar.lookupKeyForAsset(fileLocation);
    Log.d(TAG, "onMethodCall: key is "+key);
    AssetFileDescriptor fd;
    MediaPlayer mediaPlayer = new MediaPlayer();
    try {
        Log.d(TAG, "onMethodCall: found assets " + Arrays.toString(assetManager.list("assets/")));
        fd= assetManager.openFd(key);
        mediaPlayer.setDataSource(fd.getFileDescriptor(),fd.getStartOffset(),fd.getLength());
        fd.close();
        mediaPlayer.prepare();
        mediaPlayer.start();
        result.success("played successfully");
  }
  catch (Exception e){
    Log.d(TAG, "onMethodCall: exception occured "+e.toString());
    result.success("playing failed");
  }
}
Run Code Online (Sandbox Code Playgroud)

fileLocation 正确传递为

资产/河流.m4a

我检查了一下,发现注册商查找的密钥是

flutter_assets/资产/river.m4a

并且该文件存在于包中

资产/flutter_assets/资产/river.m4a

但当我运行应用程序时它仍然抛出

D/TunePlugin:onMethodCall:发生异常 java.io.FileNotFoundException:flutter_assets/assets/river.m4a

Sac*_*oma 6

在您的 pubspec.yaml 文件中添加以下内容...

flutter:
    assets:
-assets/flutter_assets/assets/river.m4a
Run Code Online (Sandbox Code Playgroud)


Gan*_*ari -1

让我惊讶的是,当我通过终端(即 Git bash)运行同一个应用程序时,它没有给我带来任何问题,并且播放的歌曲没有任何错误。当我通过 android studio 运行相同的应用程序时,它会产生 FileNotFoundException