Clip not playing any sound

◇◆丶佛笑我妖孽 提交于 2020-01-09 12:03:44

问题


Well, the title says all, I tried playing a wav file using javax.sound and nothing is happening. I have tried many different files without any luck.

public static void main(String[] args) throws IOException, UnsupportedAudioFileException, LineUnavailableException
{

    File in = new File("C:\\Users\\Sandra\\Desktop\\music\\rags.wav");
    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
    Clip play = AudioSystem.getClip();
    play.open(audioInputStream);
    FloatControl volume= (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
    volume.setValue(1.0f); // Reduce volume by 10 decibels.
    play.start();

}

回答1:


As, has already begin stated, you need to prevent the main thread from exiting, as this will cause the JVM to terminate.

Clip#start is not a blocking call, meaning that it will return (soon) after it is called.

I have no doubt that there are many ways to approach this problem and this is just a simple example of one of them.

public class PlayMusic {

    public static void main(String[] args) throws InterruptedException {
        Clip play = null;
        try {
            File in = new File("C:\\Users\\Public\\Music\\Sample Music\\Kalimba.wav");
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
            play = AudioSystem.getClip();
            play.open(audioInputStream);
            FloatControl volume = (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
            volume.setValue(1.0f); // Reduce volume by 10 decibels.
            play.start();
            // Loop until the Clip is not longer running.
            // We loop this way to allow the line to fill, otherwise isRunning will
            // return false
            //do {
            //    Thread.sleep(15);
            //} while (play.isRunning());
            play.drain();
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
            ex.printStackTrace();
        } finally {
            try {
                play.close();
            } catch (Exception exp) {
            }
        }
        System.out.println("...");
    }
}

The actual solution will depend on your needs.




回答2:


Java's sound Clip requires an active Thread to play the audio input file otherwise the application exits before the file can be played. You could add

JOptionPane.showMessageDialog(null, "Click OK to stop music");

after calling start.




回答3:


The proper way to play the audio clip is to drain the line as explained in Playing Back Audio.

So your main should look like this:

public static void main(String[] args) throws IOException,
    UnsupportedAudioFileException, LineUnavailableException
{
    File in = new File("C:\\Users\\Sandra\\Desktop\\music\\rags.wav");
    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
    Clip play = AudioSystem.getClip();
    play.open(audioInputStream);
    FloatControl volume= (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
    volume.setValue(1.0f); // Reduce volume by 10 decibels.
    play.start();
    play.drain();
    play.close();
}

play.drain() blocks until all the data is played.




回答4:


Here playing a clip

    public static void main(String[] args) throws Exception {
           File in = new File("C:\\Users\\Sandra\\Desktop\\music\\rags.wav");
           AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
           Clip play = AudioSystem.getClip();
           play.open(audioInputStream);
           FloatControl volume= (FloatControl)play.getControl(FloatControl.Type.MASTER_GAIN);
           volume.setValue(1.0f); // Reduce volume by 10 decibels.
           play.start();
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    // A GUI element to prevent the Clip's daemon Thread
                    // from terminating at the end of the main()
                    JOptionPane.showMessageDialog(null, "Close to exit!");
                }
            });
        }



回答5:


Your program is terminating before the sound has the time to be played. I would do play.start(); in some threading way (invokeLater, ...), and also find a way to wait until the sound has finished (Reimeus suggested one).

A lead :

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {

          ...

          play.start();
          JOptionPane.showMessageDialog(null, "Click OK to stop music");
        }
    });

}



回答6:


If you just want to play an audio, here's a way.

The audioFileDirectory String variable needs the correct path to your audio file, otherwise an exception will be thrown and the program won't run.

Example of having the right audio file directory in a project if using an IDE:

  1. Make a folder inside src folder, e.g: "music" and put an audio file there
  2. audioFileDirectory = "/music/name_of_audio_file";

The important part for an audio to play is that the main thread of the program needs somehow to be "alive", so the line

Thread.sleep(audio.getMicrosecondLength()/1000);

is where the main thread is "alive", and the argument audio.getMicrosecondLength()/1000 is the time that will be "alive", which is the whole length of the audio file.

public class AudioTest
{
    void playAudio() throws Exception
    {
        String audioFileDirectory = "your_audioFileDirectory";
        InputStream is = getClass().getResourceAsStream(audioFileDirectory);
        BufferedInputStream bis = new BufferedInputStream(is);
        AudioInputStream ais = AudioSystem.getAudioInputStream(bis);
        Clip audio = AudioSystem.getClip();
        audio.open(ais);
        audio.loop(Clip.LOOP_CONTINUOUSLY);
        audio.start();
        Thread.sleep(audio.getMicrosecondLength()/1000);
        audio.close();
    } // end playAudio

    public static void main(String[] args) 
    {
        try 
        {
            new AudioTest().playAudio();
        } 
        catch (Exception e) 
        {
            System.out.println("Class: " + e.getClass().getName());
            System.out.println("\nMessage:\n" + e.getMessage() + "\n");
            e.printStackTrace();
        }
    } // end main
} // end class AudioTest


来源:https://stackoverflow.com/questions/17138614/clip-not-playing-any-sound

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