Flutter Offline Audio: Cache and Play MP3s
https://ift.tt/KP90Amo
Offline audio can be the difference between an app users rely on and one they abandon. When I built Punj Surah — a Quran companion app featuring high-quality MP3 recitations, page-by-page reading, a Qibla Finder, a Salah tracker, and a Tasbeeh counter — one requirement was essential: once a recitation is downloaded, it must work anywhere. In a mosque basement, on a flight, or in a village with barely any signal. That offline experience helped the app reach more than 10,000 downloads while maintaining a 99.9% crash-free rate.
This guide covers the production-ready pattern I use: save MP3s in the app’s documents directory, play local files with just_audio, limit cache size to protect device storage, and handle network failures gracefully. The examples below are written for the latest stable versions of Flutter and Dart.
Cache first, stream second
The architecture has three layers. A download manager downloads each file once and saves it in the app’s documents directory. A cache layer uses a least-recently-used eviction policy to remove the least recently played files when the cache exceeds your chosen limit. A player layer prioritizes local files and accesses the network only when a file is missing.
Maintain a small manifest — either a JSON file or a few key-value entries — that maps each track ID to its filename and records whether the download is complete. Never play a partially downloaded file. If the app closes during a download, the manifest should indicate that the file is incomplete and needs to be downloaded again.
Step 1: Download MP3s with progress
Download each file to a temporary .part\ file first, then rename it after the download finishes. This ensures a crash or app shutdown cannot leave a partially written file that the player mistakenly treats as complete.
\`dart
import ‘dart:io’;
import ‘package:http/http.dart’ as http;
import ‘package:path_provider/path_provider.dart’;
Future downloadTrack(
String url,
String fileName, {
void Function(double progress)? onProgress,
}) async {
final dir = await getApplicationDocumentsDirectory();
final file = File(‘\${dir.path}/audio/$fileName’);
if (await file.exists()) return file; // Already cached.
final tmp = File(‘\${file.path}.part’);
final request = http.Request(‘GET’, Uri.parse(url));
final response = await http.Client().send(request);
final total = response.contentLength ?? 0;
final sink = tmp.openWrite();
int received = 0;
try {
await for (final chunk in response.stream) {
sink.add(chunk);
received += chunk.length;
if (total > 0) onProgress?.call(received / total);
}
await sink.flush();
await sink.close();
return await tmp.rename(file.path); // Atomic: complete file only.
} catch (_) {
await sink.close();
if (await tmp.exists()) await tmp.delete();
rethrow;
}
}
`\
Two details are important. First, contentLength\ may be missing for chunked responses, so check that it is available before calculating progress. Second, delete the .part\ file if the download fails. Leftover partial files are a common cause of players that appear to play but produce no sound.
Step 2: Play from the local cache
just_audio\ can play a local file path directly, enabling quick playback, seeking, and avoiding network buffering:
\`dart
import ‘package:just_audio/just_audio.dart’;
final player = AudioPlayer();
Future playCachedTrack(File file) async {
await player.stop();
await player.setFilePath(file.path);
await player.play();
}
@override
void dispose() {
player.dispose();
super.dispose();
}
`\
Always dispose of the player. An AudioPlayer\ holds native audio resources. Creating a new player for every screen visit without disposing of it can slowly drain memory — a problem users may notice before it becomes obvious in the profiler.
Step 3: Fall back to streaming when a file is not cached
The calling code chooses the playback strategy: check the cache first; if the file is missing, download and play it. If the download fails with a SocketException\, try streaming the URL directly as a last resort.
\`dart
Future playTrack(String trackId, String url, String fileName) async {
final file = File(‘\${(await getApplicationDocumentsDirectory()).path}/audio/$fileName’);
if (await file.exists()) {
await playCachedTrack(file);
return;
}
try {
final downloaded = await downloadTrack(url, fileName);
await playCachedTrack(downloaded);
} on SocketException {
// No network at all: stream it instead, it may still buffer.
await player.setUrl(url);
await player.play();
}
}
`\
This fallback sequence — cached file, fresh download, then direct streaming — helps keep an audio app usable even when network conditions are poor.
Step 4: Keep the cache under a storage budget
Audio files can consume storage quickly; a single Surah recitation may take up 15 MB. Set a cache limit, such as 500 MB, and remove the least recently played files whenever the cache exceeds it. Run the cleanup after each completed download.
\`dart
class _CacheEntry {
final File file;
final int size;
final DateTime modified;
_CacheEntry({required this.file, required this.size, required this.modified});
}
Future trimCache(Directory audioDir, {required int maxBytes}) async {
final entries = <_CacheEntry>[];
int total = 0;
await for (final entity in audioDir.list()) {
if (entity is! File || entity.path.endsWith(‘.part’)) continue;
final stat = await entity.stat();
entries.add(_CacheEntry(file: entity, size: stat.size, modified: stat.modified));
total += stat.size;
}
if (total <= maxBytes) return;
entries.sort((a, b) => a.modified.compareTo(b.modified)); // Oldest first.
for (final entry in entries) {
await entry.file.delete();
total -= entry.size;
if (total <= maxBytes) break;
}
}
`\
The two checks here are important: .part\ files are excluded so an active download is not removed while it is being written. The currently playing file should continue playing because just_audio already has it open; deleting its path on Android does not end the active playback session.
Step 5: A seek bar that feels instant
Seeking through a local file is nearly instantaneous. Connect the player’s streams to a slider to keep the UI synchronized:
\`dart
StreamBuilder(
stream: player.positionStream,
builder: (context, snapshot) {
final position = snapshot.data ?? Duration.zero;
final duration = player.duration ?? Duration.zero;
final max = duration.inMilliseconds.toDouble().clamp(1.0, double.infinity);
return Slider(
value: position.inMilliseconds.toDouble().clamp(0.0, max),
max: max,
onChanged: (value) {
player.seek(Duration(milliseconds: value.round()));
},
);
},
);
`\
Clamping the slider value protects against the brief interval when position\ is available before duration\. Without this safeguard, the slider can throw a range error on its first frame.
Checklist before you ship
-
Configure the audio session. Use the
audio_session\package to set up the platform audio session, including behaviors such as ducking on Android and silent-switch handling on iOS. Skipping this can cause playback to stop when a notification arrives. -
Set up background playback. On iOS, add
audio\toUIBackgroundModes\inInfo.plist\. On Android 14 and later, use a foreground service with themediaPlayback\type. Without the appropriate configuration, playback may stop when the screen locks. -
Request only the permissions you need. Accessing a user’s music library on Android 13 and later requires
READ_MEDIA_AUDIO\. Files your app downloads to its own documents directory do not require this permission. - Test what happens if the app closes during a download. Force-quit the app mid-download, reopen it, and confirm that the track downloads again rather than playing silence. The manifest’s completion flag is essential for this behavior.
- Test on a low-end device. Local playback is lightweight, but decoding a 20 MB file while rendering a waveform animation can still cause jank on older phones. Check performance with the DevTools performance view.
Offline audio is a feature users may not praise, but they notice when it is missing. Build the cache layer once, and you can reuse it in every audio app you create — from recitations and podcasts to language lessons.
If you’re building an audio feature and want to get it right from the start, get in touch to discuss your project.
Originally published at uzairxdev.online
HI-FI News
via DEV Community https://dev.to
October 22, 2026 at 05:43AM
-
Product on sale
Audiophile Vinyl Records Cleaning BundleOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Product on sale
Easy Start Vinyl Records Cleaning KitOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Vinyl Records Cleaner Easy Groove Concentrate€34.95 incl. VAT -
Easy Groove Super Set€199.00 incl. VAT -
Easy Groove Enzycaster – vinyl records prewash cleaner€34.95 incl. VAT -
Easy Groove Extreme MK. II- vinyl records prewash cleaner€45.00 incl. VAT -
Vinyl Records Cleaner – Easy Groove Virgin Concentrate€35.00 incl. VAT -
Easy Groove Spray&Wipe vinyl records cleaner€34.95 incl. VAT








