loadReferenceAudio static method

Future<Uint8List?> loadReferenceAudio(
  1. int surahNumber,
  2. int verseNumber
)

Load reference audio for a specific surah and verse Audio files should be stored in: assets/audio/surah_XXX/verse_YYY.pcm

Implementation

static Future<Uint8List?> loadReferenceAudio(
  int surahNumber,
  int verseNumber,
) async {
  final cacheKey = '${surahNumber}_$verseNumber';

  // Return from cache if available
  if (_audioCache.containsKey(cacheKey)) {
    return _audioCache[cacheKey];
  }

  // If another caller is already loading this asset, await that future
  if (_loadingFutures.containsKey(cacheKey)) {
    try {
      return await _loadingFutures[cacheKey];
    } catch (_) {
      // fallthrough to attempt reload
    }
  }

  final path =
      'assets/audio/surah_${surahNumber.toString().padLeft(3, '0')}/verse_${verseNumber.toString().padLeft(3, '0')}.pcm';

  final future = () async {
    try {
      final data = await rootBundle.load(path);
      final audioBytes = data.buffer.asUint8List();
      _audioCache[cacheKey] = audioBytes;
      // Single debug print when freshly loaded
      debugPrint(
          'Loaded reference audio: $path (${audioBytes.length} bytes)');
      return audioBytes;
    } catch (e) {
      debugPrint(
          'Failed to load reference audio for S$surahNumber:V$verseNumber: $e');
      return null;
    } finally {
      // remove in-flight marker
      _loadingFutures.remove(cacheKey);
    }
  }();

  _loadingFutures[cacheKey] = future;
  return await future;
}