File not Found Exception occurs when accessing flutter assets
Asked Answered
D

3

5

i am trying to write a plugin to play audio files that are stored in assets folder of flutter package and have done like this

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

fileLocation is correctly passed as

assets/river.m4a

i have checked and found out that the key which is looked up by registrar is

flutter_assets/assets/river.m4a

and the file is present in package at

assets/flutter_assets/assets/river.m4a

but still when i run the application it throws

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

Deplete answered 19/10, 2018 at 7:36 Comment(2)
Perhaps #3534337 (Android native q/a though). What code line causes the exception?Welcy
acception occurs at fd= assetManager.openFd(key);Deplete
D
-1

It came to me as a surprise that when i ran the same app through terminal i.e. Git bash it yielded me no problems and the song played without any errors. When i am running the same app through android studio it is yielding FileNotFoundException

Deplete answered 19/10, 2018 at 8:3 Comment(0)
A
6

Inside your pubspec.yaml file add this...

flutter:
    assets:
-assets/flutter_assets/assets/river.m4a
Allegro answered 19/10, 2018 at 9:25 Comment(0)
N
2

This usually happens when you try to access compressed files.

You can add the following directive to your build.gradle located at android/app/build.gradle:

aaptOptions {
    noCompress 'm4a'
}
Nones answered 2/5, 2019 at 7:52 Comment(0)
D
-1

It came to me as a surprise that when i ran the same app through terminal i.e. Git bash it yielded me no problems and the song played without any errors. When i am running the same app through android studio it is yielding FileNotFoundException

Deplete answered 19/10, 2018 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.