Simple Java MIDI example not producing any sound

南笙酒味 提交于 2019-11-30 02:42:12

问题


This simple code is not producing any sound on a couple of machines that I've used to test it. I'm running the code from within Eclipse, but I've also tried using the command line to no avail.

public static void main(String[] args)
{
    try {
        Synthesizer synthesizer = MidiSystem.getSynthesizer();
        synthesizer.open();

        MidiChannel[] channels = synthesizer.getChannels();

        channels[0].noteOn(60, 60);
        Thread.sleep(200);
        channels[0].noteOff(60);

        synthesizer.close();
    } catch (Exception e)
    {
        e.printStackTrace();
    }
}

I am able to successfully get sound by getting a Sequencer, adding MIDI events to the sequence, and playing the sequence, but I'm trying to do some real-time music effects, which the sequencer does not support.

Any ideas?

EDIT WITH SOLUTION: It turns out the problem is that, by default, the JRE doesn't come with a soundbank (interesting, then, that using the Sequencer worked, but using the Synthesizer didn't). Thanks, thejmc!

To solve the problem, I downloaded a soundbank from java.sun.com and placed it in (on WinXP) C:\Program Files\jre1.6.0_07\lib\audio (had to make the audio folder).


回答1:


Some installs of the JRE do not include the JavaSound soundbank.gm (in order to save space) so your code would not have a sound source to trigger on those machines.

Check for the existence of the soundbank on the machines that don't work. You can also put the soundbank in the same directory as your .class file and it will find it.

It is possible to add the soundbank or to upgrade the Java install on those machine - the pain of inconsistency, I know :)




回答2:


Have you tried to use different channel ? May be this discusson will get you closer to a solution...




回答3:


I've tested your code in my machine (Windows XP, JRE 1.6) and it does play the notes. Perhaps just a single note is too little to hear it. Try to add more notes. Also, try to set the volume louder.




回答4:


Just need 1 more sleep action before close synthesizer:

public static void main(String[] args)
{
    try {
        Synthesizer synthesizer = MidiSystem.getSynthesizer();
        synthesizer.open();

        MidiChannel[] channels = synthesizer.getChannels();

        channels[0].noteOn(60, 60);
        Thread.sleep(200);
        channels[0].noteOff(60);
        Thread.sleep(200);

        synthesizer.close();
    } catch (Exception e)
    {
        e.printStackTrace();
    }
}


来源:https://stackoverflow.com/questions/380103/simple-java-midi-example-not-producing-any-sound

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!