diff --git a/packages/audioplayers/lib/src/audio_cache.dart b/packages/audioplayers/lib/src/audio_cache.dart index 7acac534d..03c414493 100644 --- a/packages/audioplayers/lib/src/audio_cache.dart +++ b/packages/audioplayers/lib/src/audio_cache.dart @@ -7,6 +7,9 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart' show rootBundle; import 'package:http/http.dart' as http; import 'package:path_provider/path_provider.dart'; +import 'package:uuid/uuid.dart'; + +const _uuid = Uuid(); /// This class represents a cache for Local Assets to be played. /// @@ -45,7 +48,14 @@ class AudioCache { /// crucial). String prefix; - AudioCache({this.prefix = 'assets/'}); + /// An unique ID generated for this instance of [AudioCache]. + /// + /// This is used to load a file into an unique location in the temporary + /// directory. + String? cacheId; + + AudioCache({this.prefix = 'assets/', String? cacheId}) + : cacheId = cacheId ?? _uuid.v4(); /// Clears the cache for the file [fileName]. /// @@ -89,7 +99,7 @@ class AudioCache { final byteData = await loadAsset('$prefix$fileName'); // create a temporary file on the device to be read by the native side - final file = fileSystem.file('${await getTempDir()}/$fileName'); + final file = fileSystem.file('${await getTempDir()}/$cacheId/$fileName'); await file.create(recursive: true); await file.writeAsBytes(byteData.buffer.asUint8List()); diff --git a/packages/audioplayers/test/audio_cache_test.dart b/packages/audioplayers/test/audio_cache_test.dart index a7f159423..13d626e5c 100644 --- a/packages/audioplayers/test/audio_cache_test.dart +++ b/packages/audioplayers/test/audio_cache_test.dart @@ -8,7 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; class FakeAudioCache extends AudioCache { List called = []; - FakeAudioCache({super.prefix}); + FakeAudioCache({super.prefix, super.cacheId}); @override Future fetchToMemory(String fileName) async { @@ -55,5 +55,19 @@ void main() { await cache.clear('audio.mp3'); expect(cache.loadedFiles, {}); }); + + test('Use different location for two audio caches', () async { + const fileName = 'audio.mp3'; + final cacheA = FakeAudioCache(cacheId: 'cache-path-A'); + await cacheA.load(fileName); + expect(cacheA.loadedFiles[fileName]?.path, '//cache-path-A/audio.mp3'); + + final cacheB = FakeAudioCache(cacheId: 'cache-path-B'); + await cacheB.load(fileName); + expect(cacheB.loadedFiles[fileName]?.path, '//cache-path-B/audio.mp3'); + + await cacheA.clearAll(); + await cacheB.clearAll(); + }); }); }