'How can I prevent the app from crashing when I remove the SD card while playing a track?

I'm running the sample app just_audio_background on my Android device. https://github.com/ryanheise/just_audio/tree/master/just_audio_background

The app will be killed when I remove or unmount the SD card during playback after changing the track referenced by default to the track saved on the external SD card.

The same problem is occurring in another app that uses just_audio that we are developing. Is there a way around this?

The source code for just_audio_background has been changed in the following places.

  • The path of the external SD card is obtained by path_provider. Get it with the main function in main.dart.
    import 'package:path_provider/path_provider.dart'; //added
    
    late final directory; // added
    
        Future<void> main() async {
          await JustAudioBackground.init(
            androidNotificationChannelId: 'com.ryanheise.bg_demo.channel.audio',
            androidNotificationChannelName: 'Audio playback',
            androidNotificationOngoing: true,
          );
        
          directory = await getExternalStorageDirectories(); // added
        
          runApp(MyApp());
        }
  • I Changed the track of the first song to the track saved on the SD card with _MyAppState.
    class _MyAppState extends State<MyApp> {
      static int _nextMediaId = 0;
      late AudioPlayer _player;
      final _playlist = ConcatenatingAudioSource(children: [
    
        AudioSource.uri(
          Uri.file(directory[1].path + "/test.mp3"), // refer the track in the SD card
          tag: MediaItem(
            id: '${_nextMediaId++}',
            album: "Science Friday",
            title: "A Salute To Head-Scratching Science (30 seconds)",
            artUri: Uri.parse(
                "https://media.wnyc.org/i/1400/1400/l/80/1/ScienceFriday_WNYCStudios_1400.jpg"),
          ),
        …

With this change applied, do the following:

  1. Save the track to the specified path on the SD card, And mount the SD card on Android.
  2. Launch the app.
  3. Playlist Play the first song Science Friday. (the contents are the tracks saved on the SD card)
  4. Remove or unmount the SD card. → App crashes.

Added the log when the problem occurs.
https://pastebin.com/n5qgEejD

The start and end events are as follows.
03-01 18:57:58.914 / SD card unmounted
03-01 18:58:01.095 / App crashes

I got the log using the following device.
Moto g31(Android11)

Also, OPPO Reno A has confirmed the same problem, and it also occurs when a virtual SD card is prepared for the emulator (Pixel3 / API28).



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source