Clip not playing any sound

后端 未结 6 990
迷失自我
迷失自我 2020-12-12 06:11

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 s         


        
6条回答
  •  隐瞒了意图╮
    2020-12-12 06:34

    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
    

提交回复
热议问题