jho
jho

Reputation: 243

How to stop Xamarin iOS crashing when turning on or off Bluetooth speaker?

I've created a AVAudioSession as per the code below in my Xamarin Forms iOS app.

I then create an AVAudioEngine with a AVAudioPlayerNode that successfully plays an AVAudioFile on the iPhone built-in speaker.

However, when I turn on my Bluetooth speaker the app freezes and doesn't recover.

If the Bluetooth speaker is connected before I play the AVAudioFile, it likewise plays successfully over Bluetooth, but freezes if I turn Bluetooth off.

I was hoping I could detect the RouteChanged event when the Bluetooth turns on or off, and stop my audio playback thus possibly preventing a crash, but this event for some reason only fires when the category is changed.

Three questions:

  1. Why isn't RouteChanged being called on the Bluetooth event?

  2. Shouldn't the iPhone re-route the audio automatically between built-in speaker and Bluetooth when the Bluetooth is turned on and off anyway?

  3. Why is my app freezing?

     void Init()
     {
         AVAudioSession session = AVAudioSession.SharedInstance();
    
         session.SetCategory(AVAudioSessionCategory.Playback,
                          AVAudioSessionCategoryOptions.AllowAirPlay |
                          AVAudioSessionCategoryOptions.AllowBluetoothA2DP |
                          AVAudioSessionCategoryOptions.DuckOthers);
    
         AVAudioSession.Notifications.ObserveRouteChange(Session_RouteChanged);
    
         session.SetActive(true);
    
     }
    
     protected void Session_RouteChanged(object sender, AVAudioSessionRouteChangeEventArgs e)
     {
         AVAudioSessionRouteChangeReason reason = e.Reason;
    
         return;
     }
    

Upvotes: -2

Views: 47

Answers (1)

jho
jho

Reputation: 243

I found an answer to the problem.

When the route changed for some reason the AVAudioEngine would stop running.

As a result, my app, which was auto-calling ScheduleSegment was doing so on a stopped Engine. If I restart the Engine before performing this call, all works ok.

Upvotes: 0

Related Questions