How to properly handle accidental unplugging of audio interface?

I have a PC/Mac JUCE application which should handle audio interface mishaps properly. I.e. when the user accidentally disconnects the audio interface USB cable, the application should not crash.

I have tried to handle this by listening to AudioDeviceManager change messages where I could stop the audio device and set my application into whatever state is required to do all the required things properly.

So when I unplug my USB audio interface cable, the following happens:

The AudioDeviceManager change message listener gets called, which in turn calls the following methods:

  1. const ScopedLock try_lock( my_song_playback_lock );
  2. const ScopedLock audio_lock( AudioDeviceManager::getAudioCallbackLock() );
  3. const ScopedLock midi_lock( AudioDeviceManager::getMidiCallbackLock() );
  4. AudioDeviceManager::closeAudioDevice();
  5. AudioDeviceManager::removeAudioCallback( my_application_audio_callback_class );
  6. AudioDeviceManager::setMidiInputDeviceEnabled( midi_input_device_id, false ); // Called for every MIDI input device which is in use

Usually the next thing that happens is that for some weird reason AudioDeviceManager::audioDeviceIOCallbackInt(....) still keeps calling my_application_audio_callback_class method AudioIODeviceCallback::audioDeviceIOCallbackWithContext(.....)

I would assume that should not happen since I closed the audio device in the change listener. To make matters worse, that call happens with a new numSamples parameter, which implies that AudioDeviceManager ignored my wish to stop the audio playback and grabbed another audio device to use and kept going using that.

How should I handle this correctly?

EDIT:

This seems to work fine on Windows 10 but not on my old Mac which I was developing on. The main difference seems to be that my Windows machine has JUCE 8 and no MIDI interface, while the old Mac seems to be still using JUCE 7 and has a MIDI interface. The Mac uses JUCE 7 since the version 8 doesn’t work on it anymore. Could this be the reason for the above behavior? Was there a change in JUCE 8 how the above things were handled?

I have no idea, sorry, but I think you really should get Juce 8 working on the Mac.