Search code examples
flutterjust-audio

why just_audio caches audios from local assets?


I have over 100 audio files in an assets folder, I'm using Flutter's just_audio package for Android to create a playlist of them, like this:

List<AudioSource> children = [];
for (int i = 1; i <= 125; i++) {
  children.add(
    AudioSource.uri(
      Uri.parse(
          'asset:///assets/audio/${i.toString().padLeft(3, '0')}.mp3'),
      tag: MediaItem(id: names[i - 1], title: names[i - 1]),
    ),
  );
}
await _audioPlayer.setAudioSource(
  ConcatenatingAudioSource(
    children: children,
    useLazyPreparation: true,
  ),
  preload: false,
);

Their size is about 800MB which is more than enough to make the app so large, however just_audio caches them making the size twice as big.

I've tried to clear the cache but it caused problems since just_audio relies on it, also setting useLasyPreparation to true didn't help, why does it have to cache them, and how to deal with my storage issue?


Solution

  • (The following answer is aimed at Android as per your clarifying comment)

    This is a limitation of Flutter's assets API which provides no way to stream data directly from the asset, like what is possible with Android's native AssetManager API. In Flutter, the asset must be copied in whole before use, and just_audio works within those limitations.

    If you would like better support for streaming assets in Flutter, you can show your support on this issue in the (e.g. click the thumbs up icon to vote for it.

    Alternatively, you could consider some alternative workarounds:

    1. Host the assets on a web server and have your app download them on first launch.
    2. Keep the assets bundled with the app, but refine your strategy of clearing the cache. You could achieve this with a treadmill described here where you only keep the current and next item in the playlist at any time, and dynamically add/remove the next/previous items as playback advances to the next item. When an item drops off the treadmill, you can clear that specific file from the asset cache which you will find stored in ${(await getTemporaryDirectory()).path}/just_audio_cache with the same filename as listed in the asset bundle.