如何在Java中播放除哔声之外的声音?

时间:2015-04-18 07:11:08

标签: java beep

目前,这是" beep" (在某些操作系统上没有发出嘟嘟声)声音在Java中:

Toolkit.getDefaultToolkit().beep();

但是代码使用了计算机的" beep" / alert声音......

有没有办法替换它?

2 个答案:

答案 0 :(得分:4)

我找到了一个interesting code here,它使用了除哔哔声之外的其他声音:

import javax.sound.sampled.*;

public class SoundUtils {

  public static float SAMPLE_RATE = 8000f;

  public static void tone(int hz, int msecs) 
     throws LineUnavailableException 
  {
     tone(hz, msecs, 1.0);
  }

  public static void tone(int hz, int msecs, double vol)
      throws LineUnavailableException 
  {
    byte[] buf = new byte[1];
    AudioFormat af = 
        new AudioFormat(
            SAMPLE_RATE, // sampleRate
            8,           // sampleSizeInBits
            1,           // channels
            true,        // signed
            false);      // bigEndian
    SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
    sdl.open(af);
    sdl.start();
    for (int i=0; i < msecs*8; i++) {
      double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;
      buf[0] = (byte)(Math.sin(angle) * 127.0 * vol);
      sdl.write(buf,0,1);
    }
    sdl.drain();
    sdl.stop();
    sdl.close();
  }

  public static void main(String[] args) throws Exception {
    SoundUtils.tone(1000,100);
    Thread.sleep(1000);
    SoundUtils.tone(100,1000);
    Thread.sleep(1000);
    SoundUtils.tone(5000,100);
    Thread.sleep(1000);
    SoundUtils.tone(400,500);
    Thread.sleep(1000);
    SoundUtils.tone(400,500, 0.2);

  }
}

答案 1 :(得分:0)

只需创建一个这样的功能,并随时随地调用它,例如按钮单击或监听器。

public void alert() {

    try{

        InputStream inputStream = getClass().getResourceAsStream("/sounds/sms.wav"); //Note this is path to whatever wav file you want
            AudioStream audioStream = new AudioStream(inputStream);
            AudioPlayer.player.start(audioStream);
        }
    catch (IOException e) {
       // Whatever exception you please;
    }
       // return inputStream;

}

另请注意:Audiostream类是Java专有的,如果它是一个冗长的声音字节并且需要随时停止它,您可以通过定时器,线程中断或按钮单击任意位置调用AudioPlayer.player.stop(audioStream)