From 43eb6bda52f850d50a42c9ca98ce85ed6ac713c0 Mon Sep 17 00:00:00 2001
From: PaulPickhardt <s2137275@msx.tu-dresden.de>
Date: Thu, 29 Aug 2024 15:44:47 +0200
Subject: [PATCH] Fix green in 5 set active

---
 lib/ride/services/audio.dart | 21 +++++++++++++++++----
 1 file changed, 17 insertions(+), 4 deletions(-)

diff --git a/lib/ride/services/audio.dart b/lib/ride/services/audio.dart
index 5c3295077..c05867485 100644
--- a/lib/ride/services/audio.dart
+++ b/lib/ride/services/audio.dart
@@ -158,6 +158,7 @@ class Audio {
       ftts?.speak("Neue Route berechnet");
     }
 
+    if (ride!.userSelectedSG != null) return;
     if (ride!.calcCurrentSG == null) return;
 
     // Check if the prediction is not valid anymore.
@@ -417,9 +418,25 @@ class Audio {
     // Start a timer that executes the audio instruction 5 seconds before the traffic light turns green.
     // Subtracting 5 seconds for the countdown and 1 second for the speaking delay.
     waitForGreenTimer = Timer.periodic(Duration(seconds: countdown - 6), (timer) async {
+      if (audioSession == null) return;
+      didStartWaitForGreenInfoTimerForSg = null;
+      timer.cancel();
+      waitForGreenTimer = null;
+
+      await audioSession!.setActive(true);
+      await Future.delayed(const Duration(milliseconds: 500));
+
       await ftts!.speak("GrĂ¼n in");
       await ftts!.speak("5");
 
+      // Add some buffer because the end of speak can not be detected.
+      await Future.delayed(const Duration(milliseconds: 500));
+
+      // Needs to be checked because function is async.
+      if (audioSession == null) return;
+      // Deactivate the audio session to allow other audio to play.
+      await audioSession!.setActive(false);
+
       // Add the speed advisory instruction to the current track.
       if (tracking != null && positioning?.snap != null) {
         tracking!.addSpeedAdvisoryInstruction(
@@ -430,10 +447,6 @@ class Audio {
               lon: positioning!.snap!.position.longitude),
         );
       }
-
-      didStartWaitForGreenInfoTimerForSg = null;
-      timer.cancel();
-      waitForGreenTimer = null;
     });
   }