flutterjust-audioaudio-service

How to catch an audio file url issue?


I am using audio_service with just_audio and have constructed a minimal example repo using the tutorial code I found in the repo.

If the URL I use to initialize the AudioPlayerHandler is incorrect for any reason (hardcoded in the example code just for illustration purposes, see link below) I am unable to find a way to detect the error. There is an unhandled exception that messes up the state, and I can't figure out how to catch this and take appropriate steps in the app to let the user know there has been an error. Is there a callback or something I can listen to?

https://github.com/SarvagyaVaish/audio_service_bad_url_example/blob/master/lib/audio_player_handler.dart#L13

[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: (-1100) The requested URL was not found on this server.
#0      AudioPlayer._load (package:just_audio/just_audio.dart:785)
<asynchronous suspension>
#1      AudioPlayer._setPlatformActive.setPlatform (package:just_audio/just_audio.dart:1351)
<asynchronous suspension>


Solution

  • Here's a snippet from the "Catching player errors" section on pub.dev/packages/just_audio

    try {
      await player.setUrl("https://s3.amazonaws.com/404-file.mp3");
    } on PlayerException catch (e) {
      // iOS/macOS: maps to NSError.code
      // Android: maps to ExoPlayerException.type
      // Web: maps to MediaError.code
      // Linux/Windows: maps to PlayerErrorCode.index
      print("Error code: ${e.code}");
      // iOS/macOS: maps to NSError.localizedDescription
      // Android: maps to ExoPlaybackException.getMessage()
      // Web/Linux: a generic message
      // Windows: MediaPlayerError.message
      print("Error message: ${e.message}");
    } on PlayerInterruptedException catch (e) {
      // This call was interrupted since another audio source was loaded or the
      // player was stopped or disposed before this audio source could complete
      // loading.
      print("Connection aborted: ${e.message}");
    } catch (e) {
      // Fallback for all errors
      print(e);
    }