Reliably playing a short sound in Java

后端 未结 6 1428
时光说笑
时光说笑 2021-01-06 04:46

I am tyring to write some Java code that basically just plays a short .wav file - with \'short\' I mean a fraction of a second. (The file I use is at /usr/share/sounds/gener

6条回答
  •  滥情空心
    2021-01-06 05:05

    I suspect now that the reason my test program failed was a timing issue. Either I attempted playing the short sound before the samples were fully loaded, or the program terminated too quickly. The reason for this suspicion is that if I change the above code slightly like so:

    File soundFile = new File("/usr/share/sounds/generic.wav");
    Clip clip = AudioSystem.getClip();
    AudioInputStream inputStream = AudioSystem.getAudioInputStream(soundFile);
    clip.open(inputStream);
    
    while (System.in.read() == '\n') {
        clip.stop();
        clip.setFramePosition(0);
        clip.start();
    }
    

    then the short sound gets played correctly every time I hit enter.

提交回复
热议问题