среда, 20 марта 2013 г.

Incorrect characters in the list of audio devices in Java

Everyone knows, that audio devices are listed in Java with AudioSystem.getMixerInfo(). Mac users know, that the only sound device they have for Macintosh is Built-in Input, Built-In output and Java Sound Audio Engine, version 1.0. And only the ones who use non-latin symbols in OS, know about the problem with this function: Cyrillic letters looks like a habracadabra with it. I’m not sure about Japanese ones, has to be checked still..

Like this:



It happens because getMixerInfo() returns device data in Windows-1252 charset, but tries to output it in Windows-1251. We have to help it somehow

It might be cool to write a wrapper for javax.sound.sampled.Mixer.Info, but toString() and getName() methods in this class are final. Let’s use helper functions:

public class Shared {
 private static String OS = null;
 public static String getOsName()
 {
  if(OS == null)
   OS = System.getProperty("os.name");
     return OS;
 }
 public static boolean isWindows()
 {
    return getOsName().startsWith("Windows");
 }
 public static String toLocalString(Object info)
 {
  if(!isWindows())
   return info.toString();
  String defaultEncoding = Charset.defaultCharset().toString();
  try
  {
   return new String(info.toString().getBytes("windows-1252"), defaultEncoding);
  }
  catch(UnsupportedEncodingException ex)
  {
   return info.toString();
  }
 }
}

Then we use Shared.toLocalString(item.getName()) for every such an instance. All of the titles are ok now:


Комментариев нет:

Отправить комментарий