Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sound api - Scanning for midi devices

I'm working on a java project that receives midi events from midi hardware using the javax.sound.midi library. In the documentation, it says that MidiSystem.getMidiDeviceInfo() returns a list of all connected midi hardware. It works for me, but the problem is, it only works once. It takes a moment the first time to actually scan for the devices, but each time after that it will immediately return that same list even if new devices have been connected. Is there a way to force it to rescan? It will rescan if the application is restarted, but I don't want my users to have to restart if they connect a new midi device.

BTW, I'm using Mac OS X... it's been pointed out that behavior may be different for different OS's.

like image 569
tybro0103 Avatar asked Sep 20 '10 14:09

tybro0103


1 Answers

The MidiSystem.getMidiDeviceInfo() gets the full providers list, and extracts the info of the device from each provider.

The MIDIs provider list is recovered from the JDK underlaying class com.sun.media.sound.JDK13Services, through the static method getProviders()

public static synchronized List getProviders(Class serviceClass) Obtains a List containing installed instances of the providers for the requested service. The List of providers is cached for the period of time given by cachingPeriod . During this period, the same List instance is returned for the same type of provider. After this period, a new instance is constructed and returned. The returned List is immutable.

So, it seems that this class holds thee Providers list in a cache, wich will be reloaded after a certain period. You can set this period to a custom value using the method setCachingPeriod(int seconds). As long as I know, the default caching period is set to 60 seconds.

As an example, to refresh this cache every second, you coud add this line to your code:

com.sun.media.sound.JDK13Services.setCachingPeriod(1);

Please, note that this solution makes use of a Sun propietary class, so it could not be 100% portable.

like image 91
Tomas Narros Avatar answered Oct 10 '22 03:10

Tomas Narros