访问Flutter资源时出现文件未找到异常。

5

我正在尝试编写一个插件,用于播放存储在Flutter包的资产文件夹中的音频文件,已经进行了以下操作:

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

文件位置被正确地传递为

assets/river.m4a

我已经检查并发现,注册机所查找的关键字是

flutter_assets/assets/river.m4a

该文件位于包内的位置为

assets/flutter_assets/assets/river.m4a

但是当我运行应用程序时,仍然会抛出以下异常:

D/TunePlugin: onMethodCall: exception occured java.io.FileNotFoundException: flutter_assets/assets/river.m4a


也许这个问题可以在https://dev59.com/JXA65IYBdhLWcg3w-z1A(尽管是Android本地问答)中找到答案。哪一行代码引起了异常? - Günter Zöchbauer
异常发生在 **fd = assetManager.openFd(key);**。 - Ganesh Tiwari
3个回答

6
在您的pubspec.yaml文件中添加以下内容...
flutter:
    assets:
-assets/flutter_assets/assets/river.m4a

2
这通常发生在您尝试访问压缩文件时。您可以在位于android/app/build.gradlebuild.gradle中添加以下指令:「Original Answer」。
aaptOptions {
    noCompress 'm4a'
}

-1

让我感到惊讶的是,当我通过终端即Git bash运行同一应用程序时,它没有出现任何问题,歌曲也没有出现任何错误。但是当我通过Android Studio运行同一应用程序时,却出现了FileNotFoundException。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接