playFileAtPath method Null safety

Future<void> playFileAtPath(
  1. String path
)

Play the file at the given path

Implementation

Future<void> playFileAtPath(String path) async {
  print('Playing $path');
  final player = AssetsAudioPlayer.newPlayer();
  StreamSubscription? onFinished;
  StreamSubscription? whenPlaying;

  // Stop playback
  stopPlayback() {
    print('Playing complete for $path');
    isPlaying.add(false);
    onFinished?.cancel();
    whenPlaying?.cancel();
    player.dispose();
  }

  try {
    onFinished = player.playlistFinished.listen((finished) {
      if (finished) {
        stopPlayback();
      }
    });
    whenPlaying = player.isPlaying.listen(
      (playing) => isPlaying.add(playing),
    );
    await player.open(Audio.file(path));
  } on Exception catch (err) {
    Get.log('Error while playing $path: $err');
    stopPlayback();
  }
}