3

I have made a java program that synthesises sounds using the MIDI package in the java sound API, however, when I export it to a .jar file, the sound played is quite different to what it is when I run it in eclipse. Does anyone know why it is doing this or how to fix this problem?

A list of the instruments can be found here: http://www.hittrax.com.au/images/artists/gmgs.pdf

Below is a section of my code

try {
        Synthesizer synth = MidiSystem.getSynthesizer();
        synth.open();
        MidiChannel[] channels = synth.getChannels();
        channels[0].programChange(123); // Set the instrument to be played (integer between 0 and 127)

        channels[0].noteOn(60, 80); // Play Middle C
        Thread.sleep(duration);
        channels[0].noteOff(60);
        Thread.sleep(500);

        synth.close();

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (MidiUnavailableException e) {
        e.printStackTrace();
    }

The image below shows the audio when I record it, the first one is what the sound should be as on eclipse, the second one is what the sound is when exported to a .jar

Sound Waves

xulo
  • 440
  • 3
  • 9
  • Is the `channels[0]` vs. `channels[channel]` a copy paste typo? – Kayaman Jul 01 '15 at 04:44
  • yes it is, good pick up, ill fix that up thanks – xulo Jul 01 '15 at 04:49
  • Just a guess but maybe eclipse is defining a "javax.sound.midi.Synthesizer" property which causes getSynthesizer() to return a different default synth? – davidgiga1993 Jul 01 '15 at 04:53
  • @davidgiga1993 I think you are right, I tried printing the array, synth.getAvailableInstruments() and it came up as different (yet similar) instrument names for eclipse and the .jar, annoying because the eclipse sounds are so much better – xulo Jul 01 '15 at 05:33

1 Answers1

1

As you just found out Java returns different default synthesizer when running the jar file outside of eclipse.

This might be caused by the javax.sound.midi.Synthesizer property or a sound.properties file in the classpath.

As a workaround you could print the property value when running the application inside of eclipse and set it manually so the jar file uses the same synthesizer.

Edit:

If you want to use com.sun.media.sound.MixerSynth as default create the property

javax.sound.midi.Synthesizer=com.sun.media.sound.MixerSynth

Example:

Properties props = System.getProperties();
props.setProperty("javax.sound.midi.Synthesizer", "com.sun.media.sound.MixerSynth");
Synthesizer synth = MidiSystem.getSynthesizer();
....

More information: http://docs.oracle.com/javase/7/docs/api/javax/sound/midi/MidiSystem.html)

davidgiga1993
  • 2,695
  • 18
  • 30
  • The synthesizer in eclipse is the 'com.sun.media.sound.MixerSynth' and in Java it is 'com.sun.media.sound.SoftSynthesizer' how can I change this? – xulo Jul 01 '15 at 10:15