Search code examples
flutteraudio-playerjust-audio

Is there a way to eliminate the error when clicking the button fast


I have this code below which plays a sound every time I hit a button.

AudioPlayer player = AudioPlayer();
Future<void> playSound({required String soundStr}) async {
 player.setAsset(soundStr);
 player.play();
}

But whenever I hit the button fast, sometimes it will show this error. How can I eliminate this error? I tried adding player.stop(); but it still the same.

E/flutter ( 4312): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(abort, Loading interrupted, null, null)
E/flutter ( 4312): #0      AudioPlayer._setPlatformActive.checkInterruption (package:just_audio/just_audio.dart:1236:7)
E/flutter ( 4312): #1      AudioPlayer._setPlatformActive.setPlatform (package:just_audio/just_audio.dart:1347:11)
E/flutter ( 4312): <asynchronous suspension>
E/flutter ( 4312): 
E/flutter ( 4312): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(abort, Loading interrupted, null, null)
E/flutter ( 4312): 

Edit: I tried adding await.

Future<void> playSound({required String soundStr}) async {
 await player.setAsset(soundStr);
 await player.play();
}

If I hit the buttons fast, it will still have error. Though it is now different.

E/flutter (21654): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Connection aborted
E/flutter (21654): #0      AudioPlayer._load (package:just_audio/just_audio.dart:843:11)
E/flutter (21654): <asynchronous suspension>
E/flutter (21654): #1      AudioPlayer.load (package:just_audio/just_audio.dart:770:14)
E/flutter (21654): <asynchronous suspension>
E/flutter (21654): #2      AudioPlayer.setAudioSource (package:just_audio/just_audio.dart:745:18)
E/flutter (21654): <asynchronous suspension>
E/flutter (21654): #3      playSound (package:super_pinoy_quiz/common/generic_methods.dart:396:3)
E/flutter (21654): <asynchronous suspension>
E/flutter (21654): 

I'm using this package: just_audio: ^0.9.29 Though I tried using different package but it also encounters the same error when hitting the button fast: audioplayers: ^1.1.1


Solution

  • Both setAsset and play are future method, you can await for setting assets

      Future<void> playSound({required String soundStr}) async {
       await player.setAsset(soundStr);
       await player.play();
      }